I have difficulty with pointers and I was wondering how can we get the values of a array of strings with another function using pointers ?
My code is:
char *getName(const char *complete_name) {
char buffer[50];
strcpy(buffer, complete_name);
int i = 0;
char *p = strtok (buffer, ",");
char *array[2]; //array[0] = last name and array[1] = first name
while (p != NULL) {
array[i++] = p;
p = strtok (NULL, ",");
}
printf("%s\n", array[0]); // last name
printf("%s\n", array[1]); // first name
return *array;
}
and my main function is:
int main() {
const char *patient = "Doe,John";
char *p;
int i;
p = getName(patient);
for ( i = 0; i < 2; i++ ) {
printf("%s\n", p[i]);
}
return 0;
}
My goal is to have acces to the variable array in my main, how can I do that ?
Thank you !
buffer
and array
are variables that only exist inside the function. So returning them (directly or indirectly using pointers) are illegal.
You have two options.
or
main
and pass a pointer to the memoryOption 1: Dynamic memory
That could be:
char **getName(const char *complete_name) {
char buffer[50];
strcpy(buffer, complete_name);
int i = 0;
char *p = strtok (buffer, ",");
char **array = calloc(2, sizeof *array);
while (i < 2 && p != NULL) {
array[i] = malloc(strlen(p) + 1);
strcpy(array[i], p);
++i;
p = strtok (NULL, ",");
}
if (array[0] != NULL) printf("%s\n", array[0]); // last name
if (array[1] != NULL) printf("%s\n", array[1]); // first name
return array;
}
int main() {
const char *patient = "Doe,John";
char **p;
int i;
p = getName(patient);
for ( i = 0; i < 2 && p[i] != NULL; i++ ) {
printf("%s\n", p[i]);
}
free(p[0]);
free(p[1]);
free(p);
return 0;
}
Option 2: Memory allocated in main
and passed to the function
void getName(const char *complete_name, char split[][50]) {
char buffer[50];
strcpy(buffer, complete_name);
int i = 0;
char *p = strtok (buffer, ",");
while (i < 2 && p != NULL) {
strcpy(split[i], p);
++i;
p = strtok (NULL, ",");
}
printf("%s\n", split[0]); // last name
printf("%s\n", split[1]); // first name
}
int main() {
const char *patient = "Doe,John";
char split[2][50] = { 0 };
int i;
getName(patient, split);
for ( i = 0; i < 2; i++ ) {
printf("%s\n", split[i]);
}
return 0;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments