I found this program on-line, that claims to split a string on the format "firstName/lastName". I tested, and it works:
char *splitString(char* ptrS, char c){
while( *ptrS != c ){
if( *ptrS == '\0'){
return NULL;
}
ptrS++;
}
return ptrS;
}
int main(){
char word[100];
char* firstName;
char* lastName;
printf("Please insert a word : ");
fgets(word, sizeof(word), stdin);
word[strlen(word)-1] = '\0';
firstName = word;
lastName = splitString(word, '/');
if(lastName == NULL ){
printf("Error: / not found in string\n");
exit(-1);
}
*lastName = '\0';
lastName++;
printf("First name %s, Last name %s\n",firstName, lastName);
return(0);
}
What I'm seeing here however, is only one char array being created, and the firstName
and lastName
pointers being placed properly.Maybe it is because I'm a little confused about the relation between pointers and arrays but I have a few questions about this program:
- How many strings -as char arrays- are produced after the program is executed?
- Are the char pointers used in this program the same as strings?
- Why I can use those char pointers used as strings in
printf
? I can use char pointers as strings on every C program?
As a corollary, what's the relationship between pointers and arrays? Can they be used interchangeably?