C Pointer of array of strings garbled when retreived later -


i have read lot of answers on theoretical issues memory allocation pointer arrays, have not been able fix code...so turning you.

i have array of strings in struct, need write , read from. declared as:

typedef struct client_mod {     /* client ad_file */  char *ad_filenames[10]; /* client's current ad array index*/ unsigned int ad_index;  } client; 

then , inside function , assign values pointer:

static int get_spots (client_mod *client) {  char buf[512]; file *ptr;  if ((ptr = popen("php /media/cdn/getspot.php", "r")) != null) { /* read 1 byte @ time, bufsiz - 1 bytes, last byte used null termination. */ size_t byte_count = fread(buf, 1, 512 - 1, ptr); /* apply null termination read bytes can treated string. */ buf[byte_count] = 0; }  (void) pclose(ptr);  // parse  extracted string here... int = 0; client->ad_filenames[i] = strdup(strtok(buf,"|"));  while(client->ad_filenames[i]!= null && i<5)   {   client->ad_filenames[++i] = strdup(strtok(null,"|"));   if (client->ad_filenames[i] != null && strlen(client->ad_filenames[i]) > 5)    {   log("testing correct file names %s\n", client->ad_filenames[i]);   }  }  } 

the problem comes when retreive values later:

/* in looping code block */   log("checking file under index = %d, file %s", client->ad_index,  client->ad_filenames[client->ad_index]); 

the first 2 members of array retreived normally, after garbled. appreciate guidance. thanks! understand probablby comes undefined behaviour of assigning directly pointer, can't figure out how solve it.

i think problem assigning struct element.

 char *ad_filenames[10]; 

ad_filenames array of 10 of pointer characters.

what means memory allocation needed each index.

something client->ad_filenames[0] = strdup(var1);

strdup() both malloc() , strcpy() within function.

client should variable name. defined client type.

here working code:

 #include <stdio.h>  #include <stdlib.h>  #include <string.h>   typedef struct client_mod  {         /* client ad_file */    char *ad_filenames[10];     /* client's current ad array index*/    unsigned int ad_index;   }client1;   client1 *client;    int func( char *var1 ) {    client->ad_filenames[0] = strdup(var1);  }   int  main(void)  {      char str1[10];      client = malloc( sizeof client );       strcpy( str1, "hello" );      func( str1 );       printf("%s\n", client->ad_filenames[0] );       free(client->ad_filenames[0]);      free (client);  } 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -