I'm currently learning about strings, pointers and arrays in C. I tried to write a program where an array holds three pointers to string addresses. It all seems to work but the program behaves strangely.
Here's the code:
char** getUserDetails()
{
char* host = "localhost";
char* username = "root";
char* password = "mypassword";
// create array for holding pointers to strings
char *userDetailsHolder[3];
userDetailsHolder[0] = malloc(sizeof(char)*strlen(host));
strcpy(userDetailsHolder[0], host);
userDetailsHolder[1] = malloc(sizeof(char)*strlen(username));
strcpy(userDetailsHolder[1], username);
userDetailsHolder[2] = malloc(sizeof(char)*strlen(password));
strcpy(userDetailsHolder[2], password);
return userDetailsHolder;
}
int main()
{
char** userDetails = getUserDetails();
printf("Host: %s\nUsername: %s\nPassword: %s\n", userDetails[0], userDetails[1], userDetails[2]);
printf("Host: %s\nUsername: %s\nPassword: %s\n", userDetails[0], userDetails[1], userDetails[2]);
return 0;
}
Output: The output indicates that something went terribly wrong
Host: localhost
Username: root
Password: mypassword
Host: root
Username: localhost
Password: Host: %s
Username: %s
Password: %s
The first printf seems to work, but the second has the wrong data in it. What did I do wrong?