I’m getting confused working with character string arrays. I’m trying to fill 2 arrays in a for loop. Within each array, all elements are the same.
To conserve memory, for array_person_name I attempt to simply copy the pointer to the string stored by person_name. For array_param, the string that it stores the pointer to is always 2 characters long (e.g. “bt”) plus the null termination character , and here I also attempt to conserve memory by storing the pointer to “bt” in array_param.
Since the number of array elements, arraysize, is downloaded from a database when the program runs, I use malloc to allocate memory. Since my OS is 64 bit (Linux x86-64), I allocate 8 bytes for each of arraysize pointers. Although not shown, I free these two arrays at the end of the program.
int kk, arraysize;
char person_name[101] = "";
char * array_person_name;
char * array_param;
...
strncpy(person_name, "John Smith", 100);
arraysize = <this value is downloaded from database>;
...
array_person_name = malloc( 8 * arraysize ); /* 8 is for 64b OS */
array_param = malloc( 8 * arraysize );
for (kk = 0; kk < arraysize; kk++) {
array_person_name[kk] = &person_name;
array_param[kk] = &"bt";
}
/* test results by printing to screen */
printf("Here is array_person_name[0]: %s\n", array_person_name[0]);
printf("here is array_param[0]: %s\n", array_param[0]);
The compiler returns the warnings: warning: assignment makes integer from pointer without a cast on the two lines inside the for loop. Any idea what I’m doing wrong?
Since you want each item in
array_person_nameandarray_paramto be a pointer toperson_name/”bt”, you want achar **: