Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 256
  • Last Modified:

Dynamic String Arrays & Passing them to Functions in C

I was wondering how to go about dynamically allocating an array of strings, filling them in with values, and then sending them to a function to be processed.  And if there is a difference in manipulating the dynamic string array once passed to a function, I'd be curious to see how to do that too, please.
0
TJspliff
Asked:
TJspliff
  • 2
1 Solution
 
gj62Commented:
In C, an array of strings is really an array of pointers to strings (or more appropriately, pointers to arrays of char), and to allocate them you can do the following:

This will allocate storage for 10 strings, each having 100 chars...

char **str;
int i;

str = (char **)malloc(sizeof(char*),10);

for (i = 0; i < 10; i++)
  str[i] = (char *)malloc(sizeof(char),100);

You can fill the strings by using str[i], where i = 0 through 9...

strcpy(str[3],"This is the 4th string...");

You can have a funcion definition as:

somestringfunc(char **str)
{
  int x;

  /* the following lines will print all strings - for the 4th string, it would print:

The 4 string is This is the 4th string...

*/
  for (x = 0; x < 10; x++)
    printf("The %d string is %s\n", x+1, str[x]);
 
}

and pass your array of strings in a call simply as:

somstringfunc(str);


0
 
KocilCommented:
0
 
TJspliffAuthor Commented:
Thank you gj62! That is really good, clean code that I can understand! :)

Kocil, so it seems, I'm such a noob.  Thank you both!
0
 
TJspliffAuthor Commented:
As i commented in my question, thank you again, the code and explaination is very clear and helpfull!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now