指针,数组,字符串和malloc的用C [英] Pointers, Arrays, Strings and Malloc in C
问题描述
目前,我正在学习字符串,指针和数组在C.我试着写一个程序,一个数组持有三分,字符串的地址。这一切似乎工作,但奇怪的程序行为。
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.
这里的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;
}
输出:输出指示出事可怕的错误
Host: localhost
Username: root
Password: mypassword
Host: root
Username: localhost
Password: Host: %s
Username: %s
Password: %s
第一个的printf
似乎工作,但第二个中有错误的数据。我做了什么错了?
The first printf
seems to work, but the second has the wrong data in it. What did I do wrong?
推荐答案
的问题是,你是返回一个指向驻留在栈上的数组。 userDetailsHolder
在栈上分配,并在函数返回之后将不可用。
The problem is that you are returning a pointer to an array which resides on the stack. userDetailsHolder
is allocated on the stack and is not available after the function returns.
您可以使用的malloc
再次分配数组本身,那么这将是该函数返回后使用。
You could use malloc
once more to allocate the array itself, and then it will be available after the function returns.
这篇关于指针,数组,字符串和malloc的用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!