3

I have a C code that creates an array of char pointers as the following:

char* arr[100];

I use each element in this array to point to some string that is being calculated by another function. So basically arr[0] would point to string1 and arr[1] to string2, etc.

This works just fine. However I'm now asked to be more flexible by having the user to specify the number of strings as a parameter.

How can I do this with minimal changes to my code? I understand that I need to use malloc. However I'm getting a lot of warnings in all of the assignment statements I had before. I changed the declaration of the array as the following:

char* arr = (char*)malloc(n * sizeof(char*)); //where n is provided by user

I thought that I only needed to change the declaration. Now all of the assignment statements are giving warnings ("assignment makes integer from pointer without a cast"). The following is an example of an assignment statement:

arr[i] = str; //where str is defined as char* and is calculated by another function

Am I missing something here?

user1258126
  • 301
  • 1
  • 13

4 Answers4

10

If you're looking to create an array of char *, you need a char **arr. Think of it as an array of char * -- if you had an array of int, you would have int *. Since you have an array of char *s, you need char **.

char** arr = malloc(n * sizeof(char*));
Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
2

You are declaring arr as a pointer to char: either a single string or, if you prefer, an array of chars.

To allocate an array of pointers, declare arr as

char **arr = malloc(n * sizeof(char *));

By the way, remove the cast: it is unnecessary in C. See also Question 7.7 in the comp.lang.c FAQ.

Community
  • 1
  • 1
Danilo Piazzalunga
  • 7,590
  • 5
  • 49
  • 75
1

you want to declare arr as as char ** since you are pointing to an array of pointers. If you declare arr only as char * (not char ** or char *[]) you only have one "string".

1

Don't forget that string is an array too (char *), so u will need array of pointers, which should look like this:

char** arr = (char**)malloc(n * sizeof(char*));
Neko
  • 45
  • 1
  • 6