开发者

How to pass an array of C-Strings to a function

Normally I would just pass an array into a function, however, I am doing a homework assignment and my professor says to use an array of C-Strings and I want to use a fun开发者_如何学运维ction. However, I can not think of how to send this to a function. Any help would be great.


Pass it as a double pointer:

type myFunc(char **array) {
    ...
}


Well, since a c-string is really just an array of chars, wouldn't you just pass an array of arrays of chars?


Well, do you know the syntax for an array? Do you know the syntax for a function? How would you guess an array would be passed as an argument?

If you're not sure, take a look in your C/C++ textbook.


char **arr;

arr = malloc (sizeof (char *) * string_count);
for (i=0; i<string_count; i++)
{
  /* get string size */
  arr[i] = malloc (sizeof (char) * this_string_size);
  /* copy string into allocated */
}

function (char **arr, int string_count)
{
}

Remember to free memory after use.

OR

char *arr[NOS_OF_SRINGS];

for (i=0; i<NOS_OF_STRINGS; i++)
  arr[i] = malloc (sizeof (char) * string_length);


function (char *arr[NOS_OF_STRINGS])
{
}

Remember to free the allocated memory blocks.

OR

char arr[NOS_OF_STRINGS][STR_LENGTH];

/* copy stuffs */

function (char arr[NOS_OF_STRINGS][STR_LENGTH])
{
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜