ggkmath
ggkmath

Reputation: 4246

C Program: newbie confusion on working with character string arrays

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?

Upvotes: 0

Views: 295

Answers (3)

P.P
P.P

Reputation: 121427

You shouldn't be assuming 8 bytes because it's 64 bit. You should leave that part to C and use sizeof() operator.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490788

Since you want each item in array_person_name and array_param to be a pointer to person_name/"bt", you want a 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;

Upvotes: 3

Neil
Neil

Reputation: 5780

You're assigning a pointer to array person_name to character defined by array_person_name[kk]. What you probably meant to do was to define array_person_name as a char** type.

Upvotes: 1

Related Questions