This code aim to extract data from a JSON file:
[{ "name": "alice", "age": 30, "friends" : ["marc","max" ,"alice"] },
{"name": "john", "age": 25,"friends" : ["fr","mario" ,"Jim"]}]
and store the data into a structure so this is the code:
static int c ;
typedef struct {
char name[25] ;
int age ;
char *amis ;
} personne ;
static personne * PerArray;
static size_t n_objects;
static int n_friends ;
void ShowInfo ( int n_friends);
int main(int argc, char **argv) {
FILE *fp;
char buffer[1024];
struct json_object *parsed_json;
struct json_object *name;
struct json_object *age;
struct json_object *friends;
struct json_object *friend;
size_t n_friends;
struct json_object *parsed_json_1;
static size_t n_objects;
size_t j;
size_t i;
fp = fp = fopen("file.json","r");
if ( fp == NULL)
{
printf("UNable to open file\n");
exit(EXIT_FAILURE);
}
fread(buffer, 1024, 1, fp);
fclose(fp);
parsed_json = json_tokener_parse(buffer);
n_objects = json_object_array_length(parsed_json);
PerArray = (personne *) malloc (n_objects* sizeof(personne)) ;
for(i=0;i<2;i++)
{
parsed_json_1 = json_object_array_get_idx(parsed_json,i);
json_object_object_get_ex(parsed_json_1, "name", &name);
json_object_object_get_ex(parsed_json_1, "age", &age);
json_object_object_get_ex(parsed_json_1, "friends", &friends);
strcpy(PerArray[i].name ,json_object_get_string(name));
printf("Name: %s\n", PerArray[i].name);
PerArray[i].age = json_object_get_int(age) ;
printf("Age: %d\n", PerArray[i].age);
n_friends = json_object_array_length(friends);
printf("Found %lu friends\n",n_friends);
PerArray[i].amis = malloc(sizeof(char) * n_friends);
for(j=0 ; j< n_friends ; j++)
{
friend = json_object_array_get_idx(friends, j);
printf("%zu. %s\n",j+1,json_object_get_string(friend));
strcpy(PerArray[i].amis[j] ,json_object_get_string(friend));
printf("%zu. %s\n",j+1,PerArray[i].amis[j]);
}
}
}
I have error of segmentation fault and normally the fault is in this line:
strcpy(PerArray[i].amis[j] ,json_object_get_string(friend));
I'm just putting the string friend in the structure by using strcpy.
Can anyone help?
This is wrong, PerArray[i].amis[j]
points nowhere.
strcpy(PerArray[i].amis[j], json_object_get_string(friend));
You probably want this:
typedef struct {
char name[25] ;
int age ;
char **amis ; // two stars here, you need a pointer to a pointer to char
} personne ;
...
PerArray[i].amis = malloc(sizeof(char**) * n_friends);
// now PerArray[i].amis points to an array of n_friends pointers to char*
...
const char *pfriend = json_object_get_string(friend);
PerArray[i].amis[j] = malloc(strlen(pfriend) + 1);
strcpy(PerArray[i].amis[j], pfriend);
There may be other problems though.