Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在char*数组中存储字符串时出错_C_Arrays_String - Fatal编程技术网

在char*数组中存储字符串时出错

在char*数组中存储字符串时出错,c,arrays,string,C,Arrays,String,当我编译并运行以下代码时,代码会运行 #include<stdio.h> #include<string.h> #include<stdlib.h> int main(){ char* array[1]; scanf("%s",array[0]); return 0; } #包括 #包括 #包括 int main(){ 字符*数组[1]; scanf(“%s”,数组[0]); 返回0; } 但是下面的代码没有运行。它显示了分段错误

当我编译并运行以下代码时,代码会运行

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(){
    char* array[1];
    scanf("%s",array[0]);
    return 0;
}
#包括
#包括
#包括
int main(){
字符*数组[1];
scanf(“%s”,数组[0]);
返回0;
}
但是下面的代码没有运行。它显示了分段错误。原因是什么

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(){
    char* array[2];
    scanf("%s",array[0]);
    scanf("%s",array[1]);
    return 0;
}
#包括
#包括
#包括
int main(){
字符*数组[2];
scanf(“%s”,数组[0]);
scanf(“%s”,数组[1]);
返回0;
}
我的输入是第一种情况下的bond和 詹姆斯
第二个

数组[1]
数组[1]
中的键是统一的指针。因此,您正在将数据写入无效或未定义的位置。指针需要引用分配的内存

这两个代码片段都不正确,但关于统一化指针,它可能包含合法地址或无效地址,但在任何情况下都没有定义地址

char array[2][64];
scanf("%63s",array[0]);
scanf("%63s",array[1]);

两者都是UB,因为未初始化/分配数组[]。数据类型错误。您需要的是char[],而不是char*[]。确保数组有空间容纳输入数据,并限制读取的字符数。字符行[1024];fgets(生产线、生产线尺寸、标准尺寸);这是一个简单的方法。PS:第一个版本只能靠运气工作。数组为1个指针(通常为4或8个字节)分配空间。尝试为程序提供长度超过8字节的字符串,然后尝试打印它。;)@SahilKumar
char*数组[2]可能重复;数组[0]=“我的”;scanf(“%s”,数组[0])
是UB的另一种形式。你为什么不发表你的意见?