Im a beginner and at school we have task to split a char array by using pointer. I want to split the name and the birthday (delimiter = '.'). My solution works perfect for the name but doing it for the birthday i get a segmentation fault.
int main(int argc, char *argv[])
{
char *fullname;
char *name;
char *lastname;
char *birthday;
char *day;
fullname = argv[1];
birthday = argv[2];
int i = 0;
int y = 0;
int z = 0;
while(fullname[i] != '.'){
char x = fullname[i];
name[i] = x;
fullname[i] = ' ';
i++;
}
i++;
while(fullname[i] != '\0'){
char x = fullname[i];
lastname[y] = x;
fullname[i] = ' ';
i++;
y++;
}
while(birthday[z] != '.'){
char b = birthday[z];
day[z] = b;
z++;
}
}
Input in commandline (./a is the exe file on cygwin):
./a mister.gold 11.05.2005
Output:
segmentation fault
When i launch the code without the last loop my output is:
mister
gold
char *name ;
char *lastname;
Two char array pointer , but what do they point two? nothing so you are basically trying to access a memory you don't own to allocate memory for them you should do :
// assuming the maximum size if 512 for example or you can give it any size you think is enough
char *name =malloc(512);
char *lastname=malloc(512);
now they point to something you can access & modify
after you are done using them you should deallocate the dynamic allocated memory like this
free(lastname);
free(name);