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?
source to share
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 .
source to share