Travis Pessetto
Travis Pessetto

Reputation: 3298

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 function. However, I can not think of how to send this to a function. Any help would be great.

Upvotes: 0

Views: 964

Answers (4)

phoxis
phoxis

Reputation: 61910

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])
{
}

Upvotes: 0

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

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.

Upvotes: 0

Dogmatixed
Dogmatixed

Reputation: 794

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

Upvotes: 0

Dair
Dair

Reputation: 16240

Pass it as a double pointer:

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

Upvotes: 3

Related Questions