gpt4 book ai didi

c - 我在将 malloc 与字符串指针一起使用时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:45 25 4
gpt4 key购买 nike

当我尝试使用带有字符串指针的 malloc 进行扫描时,它给出了一个段错误

main(){
char *a;
a = (char)malloc(50);
printf("enter a string\t");
scanf("%s", a);
printf("%s\n", a);
}

最佳答案

a = (char)malloc(50);

在这里,您打算将其类型转换为 char * 而不是 char

注意最好不要强制转换malloc的返回类型。参见 Do I cast the result of malloc?

关于c - 我在将 malloc 与字符串指针一起使用时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632329/

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