I have a structure that has name and surname. I want to write two pointers to array (infoArr). Here's the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char* surname;
char* name;
}Info;
int main(int argc, const char * argv[]) {
Info **infoArr = calloc(2, sizeof(Info*));
char* name1 = "Ian";
char* surname1 = "Jones";
char* name2 = "Ann";
char* surname2 = "Stephens";
Info *info = malloc(sizeof(Info));
info->surname=surname1;
info->name=name1;
infoArr[0]=info;
printf("infoArr[0]: %s %s\n",infoArr[0]->surname,infoArr[0]->name);
info->surname=surname2;
info->name=name2;
infoArr[1]=info;
printf("infoArr[1]: %s %s\n\n",infoArr[1]->surname,infoArr[1]->name);
free(info);
printf("infoArr[0]: %s %s\n",infoArr[0]->surname,infoArr[0]->name);
printf("infoArr[1]: %s %s\n",infoArr[1]->surname,infoArr[1]->name);
free(infoArr);
return 0;
}
And as a result I receive this:
infoArr[0]: Jones Ian
infoArr[1]: Stephens Ann
infoArr[0]: Stephens Ann
infoArr[1]: Stephens Ann
What is wrong here? Why it changes first element then?