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?
sizeof(char *)strncpy()and zero-fill the tail end of yourperson_namearray (again, because the initializer also zero-filled it), then use:strncpy(person_name, "John Smith", sizeof(person_name));. In general, usingsizeof()helps. You do need to be cautious about whether you have an array name or just a pointer.sizeof(array)gives the size of the array, butsizeof(pointer)gives the size of a pointer, not the size of the array. Function arguments are pointers, not arrays. Be cautious about usingsizeof()on function arguments, and pass arrays sizes with strings.100in strncpy to avoid potential errors if more than 100 characters are copied (I'm not trying to pad with spaces). My intent is to simply copyJohn Smithintoperson_name, along with a null character automatically included by the compiler. I'm not sure if your comment impacts this.