473,654 Members | 3,107 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning a string array from a function

Hi,

I'd like to return an (arbitrary length) string array from a function so
that after calling the array I've got a list of strings I can access.

After much perusing of the internet I found a related answer here (by
Eric Sosman) which involved creating an array of pointers and using
that, so it looks something like:
void foo(char *sptr[], int items)
{
char buff[50];
while (--items >= 0)
{
sprintf (buff, "foo%d", items);
sptr[items] = malloc(strlen(b uff) + 1);
if (sptr[items] == NULL)
exit(0);
strcpy (sptr[items], buff);
}
}

int main(void)
{
int total = 10;
char *p[total];

foo(p, total);

printf(p[1]);

return 0;
}
This works a treat (I can access my strings, e.g. the printf line) but
how would I do a similar thing if I don't know how long my list is going
to be? E.g. "total" only gets found out inside foo.

Thanks a lot,
Adam

--
Adam Richardson
Carpe Diem
Sep 2 '07 #1
19 1829

"Adam" <ne**@snowstone .org.ukwrote in message
news:48******** ******@snowston e.org.uk...
Hi,

I'd like to return an (arbitrary length) string array from a function so
that after calling the array I've got a list of strings I can access.

After much perusing of the internet I found a related answer here (by
Eric Sosman) which involved creating an array of pointers and using
that, so it looks something like:
void foo(char *sptr[], int items)
{
char buff[50];
while (--items >= 0)
{
sprintf (buff, "foo%d", items);
sptr[items] = malloc(strlen(b uff) + 1);
if (sptr[items] == NULL)
exit(0);
strcpy (sptr[items], buff);
}
}

int main(void)
{
int total = 10;
char *p[total];

foo(p, total);

printf(p[1]);

return 0;
}
This works a treat (I can access my strings, e.g. the printf line) but
how would I do a similar thing if I don't know how long my list is going
to be? E.g. "total" only gets found out inside foo.

Thanks a lot,
Adam
char **foo(int items)
{
char **answer;
char buff[100];
int i;

answer = malloc(items * sizeof(char *));
if(!answer)
goto error_exit;
/* needed for clean up, mustn't have non-null garbage pointers */
for(i=0;i<items ;i++)
answer[i] = 0;
for(i=0;i<items ;i++)
{
sprintf(buff, "foo %d", i):
answer[i] = malloc(stren(bu ff) + 1);
if(!answer[i])
goto error_exit;
strcpy(answer[i], buff);
}
return answer;
error_exit:
if(answer)
for(i=0;i<items ;i++)
free(answer[i]);
free(answer);
/* maybe print error message / terminate here */
return 0;
}

Sep 2 '07 #2
In article <Mt************ *************** ***@bt.com>,
Malcolm McLean <re*******@btin ternet.comwrote :
>"Adam" <ne**@snowstone .org.ukwrote in message
news:48******* *******@snowsto ne.org.uk...
>I'd like to return an (arbitrary length) string array from a function so
that after calling the array I've got a list of strings I can access.
answer = malloc(items * sizeof(char *));
if(!answer)
goto error_exit;
/* needed for clean up, mustn't have non-null garbage pointers */
Hmmm. Adam's question didn't -sound- like textbook homework, that you
needed to use a goto to down-grade the code quality so as to
down-grade the marks of anyone who copied it literally.
--
I was very young in those days, but I was also rather dim.
-- Christopher Priest
Sep 2 '07 #3
In message <Wb************ *************** ***@comcast.com >, Eric Sosman
wrote:
Adam wrote:
I'd like to return an (arbitrary length) string array from a function so
that after calling the array I've got a list of strings I can access.
^^^^^ function

[snip discussion]

Thanks a lot for the helpful info. I'll go away and do some pondering
about the best course of action. :)
Are you using a C99 compiler?
Yep, GCC, -std=c99.

Thanks,
Adam

--
Adam Richardson
Carpe Diem
Sep 2 '07 #4
Adam <ne**@snowstone .org.ukwrites:
In message <Wb************ *************** ***@comcast.com >, Eric Sosman
wrote:
[...]
> Are you using a C99 compiler?

Yep, GCC, -std=c99.
Then you're using a compiler that implements most, but not all, of C99.
See <http://gcc.gnu.org/c99status.html> .

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 2 '07 #5
In message <Wb************ *************** ***@comcast.com >, Eric Sosman
wrote:
Adam wrote:
I'd like to return an (arbitrary length) string array from a
function so that after calling the array I've got a list of strings
I can access.
[snip]
After much perusing of the internet I found a related answer here
(by Eric Sosman) which involved creating an array of pointers and
using that, so it looks something like:

void foo(char *sptr[], int items)
{
char buff[50];
while (--items >= 0)
{
sprintf (buff, "foo%d", items);
sptr[items] = malloc(strlen(b uff) + 1);
if (sptr[items] == NULL)
exit(0);
strcpy (sptr[items], buff);
}
}
[but how can I do it without specifying "items"?]
[snip]
>
Another way is for foo() to allocate the sptr "array" by
itself, using malloc().
OK, I've been thinking a bit more about this and trying to come to terms
with pointers to pointers and malloc - neither of which I've used
before! However, I'm stuck.

Thanks to Malcolm, who's example I've butchered to try and get working
(I've removed the error-checking etc to try and get it down to
fundamentals, but I realise that's important):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void foo(char **ptr)
{
char **answer;
char buff[100];
int i;
int items = 10;

answer = malloc(items * sizeof(char *));

for(i=0;i<items ;i++)
{
sprintf(buff, "foo %d", i);
answer[i] = malloc(strlen(b uff) + 1);
strcpy(answer[i], buff);
}

printf(answer[2]);

ptr = answer;
}

int main(void)
{
char *listofptrs;

foo(&listofptrs );

printf("5) %s",listofptr s[5]);

return 0;
}

answer[2] gets displayed OK, but everything goes nasty before
listofptrs[5] (and the compiler spouts warnings about the printf line
not being right).

On the face of it, since listofptrs[5] is a pointer to the string, I'd
have thought I ought to use *listofptrs[5] but I get an error about
misuse of "unary *".

I'm sure I'm doing something stupid wrong, but I can't work it out. Any
pointers welcome! ;)

Thanks,
Adam

--
Adam Richardson
Carpe Diem
Sep 5 '07 #6
Adam wrote:

OK, I've been thinking a bit more about this and trying to come to
terms with pointers to pointers and malloc - neither of which I've
used before! However, I'm stuck.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void foo(char **ptr)
{
char **answer;
char buff[100];
int i;
int items = 10;

answer = malloc(items * sizeof(char *));

for(i=0;i<items ;i++)
{
sprintf(buff, "foo %d", i);
answer[i] = malloc(strlen(b uff) + 1);
strcpy(answer[i], buff);
}

printf(answer[2]);

ptr = answer;
ptr is a local pointer. Nothing you do to it in foo() will be reflected
back in main().

}

int main(void)
{
char *listofptrs;
In spite of the name, listofptrs is a single pointer to char. NOT what
you want.
foo(&listofptrs );

printf("5) %s",listofptr s[5]);
listofptrs[5] would be at best a single char, not a string.
return 0;
}
I wouldn't do it this way for real, but here's a way with the least
amount of fiddling with your example that achieves the goal:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void foo(char ***ptr)
{
char **answer;
char buff[100];
int i;
int items = 10;

answer = malloc(items * sizeof(char *));

for(i=0;i<items ;i++)
{
sprintf(buff, "foo %d", i);
answer[i] = malloc(strlen(b uff) + 1);
strcpy(answer[i], buff);
}

printf(answer[2]);

*ptr = answer;
}

int main(void)
{
char **listofptrs;

foo(&listofptrs );

printf("5) %s",listofptr s[5]);

return 0;
}

Brian

Sep 5 '07 #7
On 2007-09-05, Adam <ne**@snowstone .org.ukwrote:
OK, I've been thinking a bit more about this and trying to come to terms
with pointers to pointers and malloc - neither of which I've used
before! However, I'm stuck.

Thanks to Malcolm, who's example I've butchered to try and get working
(I've removed the error-checking etc to try and get it down to
fundamentals, but I realise that's important):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void foo(char **ptr)
{
char **answer;
char buff[100];
int i;
int items = 10;

answer = malloc(items * sizeof(char *));

for(i=0;i<items ;i++)
{
sprintf(buff, "foo %d", i);
answer[i] = malloc(strlen(b uff) + 1);
strcpy(answer[i], buff);
}

printf(answer[2]);

ptr = answer;
}

int main(void)
{
char *listofptrs;

foo(&listofptrs );

printf("5) %s",listofptr s[5]);

return 0;
}

answer[2] gets displayed OK, but everything goes nasty before
listofptrs[5] (and the compiler spouts warnings about the printf line
not being right).

On the face of it, since listofptrs[5] is a pointer to the string, I'd
have thought I ought to use *listofptrs[5] but I get an error about
misuse of "unary *".
[snip]

Given the declaration

char *listofptrs"

listofptrs[5] is a char. To have listofptrs[5] be a char*, you can use
the declaration

char **listofptrs

With that change to the declaration, you need to change

void foo(char **ptr)

to

void foo(char ***ptr)

and inside the function foo change

ptr = answer;

to

*ptr = answer;
Sep 5 '07 #8
On 5 Sep, 23:36, "Default User" <defaultuse...@ yahoo.comwrote:
ptr is a local pointer. Nothing you do to it in foo() will be reflected
back in main().
Of course. I'd had a feeling there was something wrong with that
expression. If I'd nailed it down I might have solved my problem! :)
I wouldn't do it this way for real, but here's a way with the least
Any alternative suggestions are welcome :)

Thanks,
Adam

Sep 6 '07 #9
Adam wrote:
On 5 Sep, 23:36, "Default User" <defaultuse...@ yahoo.comwrote:
ptr is a local pointer. Nothing you do to it in foo() will be
reflected back in main().

Of course. I'd had a feeling there was something wrong with that
expression. If I'd nailed it down I might have solved my problem! :)
I wouldn't do it this way for real, but here's a way with the least

Any alternative suggestions are welcome :)
It's poor practice to use a magic number defined in the worker
function. How would the caller know what the value of "items" is?

One thing to consider is whether you want to do all the allocating in a
separate function. The caller then has to deallocate it.

If you do, then you at least need to tell the caller how many items
have been indicated. Either a return value or another parameter is the
way to do that.

Brian
Sep 6 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
1882
by: Justin Naidl | last post by:
class Foo { protected: char foo_stuff; public: char* get_foo_stuff(); } Given the above example. What I want to know is the "proper/standard" way
1
3324
by: john | last post by:
Relatively new to C coding, so any help would greatly be appreciated. I'm having problems try to return my string array from my parsing function. When I do a printf I am getting the correct value for my first element but my subsequent printf's will return garbage. Can someone let me know what I am doing wrong. Thanks in advance. -jlewis
10
3155
by: Pete | last post by:
Can someone please help, I'm trying to pass an array to a function, do some operation on that array, then return it for further use. The errors I am getting for the following code are, differences in levels of indirection, so I feel it must have something to do with the way I am representing the array in the call and the return. Below I have commented the problem parts. Thanks in advance for any help offered. Pete
3
1847
by: Carramba | last post by:
hi! the code is cinpiling with gcc -ansi -pedantic. so Iam back to my question Iam trying to make program were I enter string and serach char. and funktion prints out witch position char is found this is done if funktion serach_char. so far all good what I want do next is: return, from funktion, pointer value to array were positions ( of found char) is stored. and print that array from main. but I only manage to print memory adress to...
5
19581
by: Stacey Levine | last post by:
I have a webservice that I wanted to return an ArrayList..Well the service compiles and runs when I have the output defined as ArrayList, but the WSDL defines the output as an Object so I was having a problem in the calling program. I searched online and found suggestions that I return an Array instead so I modified my code (below) to return an Array instead of an ArrayList. Now I get the message when I try to run just my webservice...
5
5474
by: shyam | last post by:
Hi All I have to write a function which basically takes in a string and returns an unknown number( at compile time) of strings i hav the following syntax in mind char *tokenize(char *) is it ok?
4
15000
by: John | last post by:
Hi I need to return an array of string in my own split function (access 97). I have defined the function as below but I get err on 'As String()'. What can I do to make the function return an array of strings? Public Function Split(ByVal strIn As String, Optional strDelimiter As String = " ") As String() Thanks
13
2545
by: Karl Groves | last post by:
I'm missing something very obvious, but it is getting late and I've stared at it too long. TIA for responses I am writing a basic function (listed at the bottom of this post) that returns data from a query into an array. The intent is that the following code:
0
4081
by: anuptosh | last post by:
Hi, I have been trying to run the below example to get a Oracle Array as an output from a Java code. This is an example I have found on the web. But, the expected result is that the code should return me Array element type code 1, but it is returning me type code 12 and the array in a junk or unreadable format . Our environment is JDK 1.4, ojdbc14.jar and Oracle 8i Not able to find out what they problem is and am not able to change the...
8
2211
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
0
8290
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8707
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8482
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8593
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5622
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4149
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2714
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1593
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.