C: newbie confusion when dealing with character arrays

I am confused about working with character arrays. I am trying to populate 2 arrays in a for loop. Inside each array, all elements are the same.

To save memory, for array_person_nameI'm trying to just copy the pointer to a string stored in person_name. For the array_paramline in which it stores the pointer, it always has a length of 2 characters (for example, "bt") plus a zero-termination character, and here I am also trying to save memory by saving the pointer to "bt" in array_param,

Since the number of array elements is arraysizeloaded from the database when the program starts, I use malloc to allocate memory. Since my OS is 64-bit (Linux x86-64), I allocate 8 bytes for each of the pointers arraysize. 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 warnings: warning: assignment makes integer from pointer without a castfor two lines inside a for loop. Any idea what I'm doing wrong?

0
source share
3 answers

Since you want each element in array_person_nameand to be array_parama pointer to person_name/ "bt", you need char **:

char **array_person_name;

array_person_name = malloc(arraysize * sizeof(*array_person_name));

for (int i=0; i<arraysize; i++)
    array_person_name[i] = person_name;
+3
source

person_name , array_person_name [kk]. , , , , - array_person_name char **.

+1

You should not accept 8 bytes because it is 64 bits. You must leave this part in C and use the operator sizeof().

+1
source

Source: https://habr.com/ru/post/1614892/


All Articles