我一直试图理解malloc和字符串,有人可以帮我这个 - 我得到一个错误的指针错误
char password[100];
char *key[2];
int textlen, keylen, i, j, k, t, s = 0;
printf("password:\n") ;
scanf("%s",password);
keylen = strlen(password) + 1;
for(i=0; i < keylen; i++)
{
key[i] = (char*)malloc(keylen * sizeof(char));
strcpy(key[i], password);
}
printf("The key is:\n\t %s", key);
Run Code Online (Sandbox Code Playgroud)
djg*_*ndy 14
我想你需要试着去了解自己想要实现的目标.你不需要key [2]数组,我认为你在那里让你感到困惑,因为你还不知道指针是如何工作的.以下应该工作(未经测试)
// Allow a password up to 99 characters long + room for null char
char password[100];
// pointer to malloc storage for password
char *key;
int textlen, keylen, i, j, k, t, s = 0;
// Prompt user for password
printf("password:\n") ;
scanf("%s",password);
// Determine the length of the users password, including null character room
keylen = strlen(password) + 1;
// Copy password into dynamically allocated storage
key = (char*)malloc(keylen * sizeof(char));
strcpy(key, password);
// Print the password
printf("The key is:\n\t %s", key);
Run Code Online (Sandbox Code Playgroud)
The problem that you have is here:
printf("The key is:\n\t %s", key);
Run Code Online (Sandbox Code Playgroud)
You are passing the pointer array to printf, while what you would want to do is
printf("The key is:\n\t %s", key[0]);
Run Code Online (Sandbox Code Playgroud)
Yet another problem is that you allocte as much pointers as you have characters in your password, so you overwrite the pointer array you reserved, because key has only room for two pointers, not for N, which is the primary cause for your "bad pointer" problem.
And another thing, which is not related to this error is, that you shouldn't cast malloc as well as you don't need to multiply with sizeof(char) as this will always be 1 by definition.
| 归档时间: |
|
| 查看次数: |
65776 次 |
| 最近记录: |