gpt4 book ai didi

c - Malloc 字符串数组 - C

转载 作者:太空狗 更新时间:2023-10-29 17:15:34 25 4
gpt4 key购买 nike

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

最佳答案

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

关于c - Malloc 字符串数组 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18916432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com