Reputation: 23
I have this array which is correct, but I need the values and size to be variable. Is this possible? If so, how?
const char *labels[] = { "Group A", "Group B", "Group C", "Group D", "Group E", "Group F", "Group G", "Group H" };
It has to be a const char *
array because it is being used as a stringArray parameter, which won't take anything less complicated.
Any help would be appreciated. Please keep in mind that I am a student developer.
Upvotes: 1
Views: 799
Reputation: 28664
It has to be a const char *array because it is being used as a stringArray parameter, which won't take anything less complicated.
You can pass char*
to function expecting const char*
.
Given that, maybe you can try something like this:
char**arr = malloc(ARRAY_LEN * sizeof(char*));
for (i=0; i<ARRAY_LEN; i++)
{
arr[i] = malloc(EACH_STRING_LEN);
if(arr[i]==NULL)
handleError();
strcpy(arr[i],"test"); // put some string in i-th array
}
and freeing part:
for (i = 0; i < ARRAY_LEN; i++) {
free(arr[i]);
}
free(arr);
Upvotes: 1
Reputation: 105
c arrays do not have variable size. If you need this functionality, you have to use a different data structure
What do you mean by "it is being used as a stringArray parameter, which won't take anything less complicated."?
Upvotes: 0