C语言 Malloc 一个字符串数组 - C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18916432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:29:49  来源:igfitidea点击:

Malloc a string array - C

carraysstring

提问by Dex Dave

I have been trying to understand malloc and strings, can someone help me with this please - I get a bad pointer error

我一直在尝试理解 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);

回答by djgandy

I think you need to try and understand yourself what you are trying to achieve. You don't need the key[2] array and I think you are confusing yourself there as you don't yet understand how pointers work. The following should work (untested)

我认为您需要尝试了解自己要实现的目标。您不需要 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);

回答by Devolus

The problem that you have is here:

您遇到的问题在这里:

 printf("The key is:\n\t %s", key);

You are passing the pointer array to printf, while what you would want to do is

您将指针数组传递给 printf,而您想要做的是

 printf("The key is:\n\t %s", key[0]);

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 keyhas only room for two pointers, not for N, which is the primary cause for your "bad pointer" problem.

另一个问题是,您分配的指针与密码中的字符一样多,因此您覆盖了您保留的指针数组,因为key只有两个指针的空间,而不是 N,这是“坏指针”的主要原因问题。

And another thing, which is not related to this error is, that you shouldn't cast mallocas well as you don't need to multiply with sizeof(char)as this will always be 1 by definition.

与此错误无关的另一件事是,您不应该malloc像不需要乘以sizeof(char)一样进行强制转换,因为根据定义,这将始终为 1。