Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.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
C++ 将零复制到字符数组中也会清除其他字符数组_C++_Arrays_File Io_Buffer - Fatal编程技术网

C++ 将零复制到字符数组中也会清除其他字符数组

C++ 将零复制到字符数组中也会清除其他字符数组,c++,arrays,file-io,buffer,C++,Arrays,File Io,Buffer,x从ifstream缓冲区读取30字节的文件。y存储一个随机字符串 char x[30]; char* y[5]; int count = 0; ifstream i("test.txt", std::ifstream::binary); 对于本例,假设文件包含小于或等于150字节的数据 为什么这种情况不断发生?即使使用memset,我也会观察到同样的行为。如何修复它?由于y[0]是一个指针,它可以指向(或进入)x。你观察到的行为表明确实如此。如果y[0]指向(或进入)x,那么更改x的内容将更

x从ifstream缓冲区读取30字节的文件。y存储一个随机字符串

char x[30];
char* y[5];
int count = 0;
ifstream i("test.txt", std::ifstream::binary);
对于本例,假设文件包含小于或等于150字节的数据


为什么这种情况不断发生?即使使用memset,我也会观察到同样的行为。如何修复它?

由于
y[0]
是一个指针,它可以指向(或进入)
x
。你观察到的行为表明确实如此。如果
y[0]
指向(或进入)
x
,那么更改
x
的内容将更改
y[0]
指向的内容。

如何将
x
y
(或
y[0]
)关联?请提供一个可验证(可编译)的示例?我打赌您在读取循环中将y[0]指定给x,您不是在分配内存和复制,而是在为
char*y[5]
的5个元素分配内存,不是吗?。。。y[0]=malloc(SOME_VAL)。。。y[4]=malloc(某些值);提示:
y
数组是指针数组,不是字符数组。
while (i.read(x, sizeof(x)) {
    y[count] = x;
    printf("%s\n", y[0]); //This prints "test\n"
    bzero(x, sizeof(x)); //Clear the contents of array x
    printf("%s\n", y[0]); //This prints "\n"
    count++
}