Changing a static array to a dynamic one with minimal changes?
I have C code that creates an array of char pointers like this:
char* arr[100];
I am using each element in this array to point to some string that is calculated by another function. So basically arr [0] points to line1 and arr [1] to line2 and so on.
This works great. However, I am now asked to be more flexible by specifying the number of lines as a parameter.
How can I do this with minimal changes to my code? I understand that I need to use malloc. However, I am getting a lot of warnings in all the assignment statements I have had before. I changed the array declaration as follows:
char* arr = (char*)malloc(n * sizeof(char*)); //where n is provided by user
I thought I only needed to change the ad. Now all assignment instructions give warnings ("assignment makes an integer from a pointer without a cast"). Below 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?
If you want to create an array char *
you will need char **arr
. Think of it as an array char *
- if you have an array int
, you will int *
. Since you have an array char *s
, you need char **
.
char** arr = malloc(n * sizeof(char*));
You declare arr
as a pointer to char
: either a single string, or an array char
s if you prefer.
To allocate an array of pointers, declare arr
as
char **arr = malloc(n * sizeof(char *));
By the way, remove the cast: unnecessary in C. See also Question 7.7 in the comp.lang.c FAQ .
you want to declare arr
as char **
as you are pointing to an array of pointers. If you arr
only declare as char *
(not char **
or char *[]
), you only have one line.
Don't forget that the string is also an array ( char *
), so you need an array of pointers, which should look like this:
char** arr = (char**)malloc(n * sizeof(char*));