我有一个带有动态数组的结构:
struct mystruct {
int count;
int *arr;
} mystruct_t;
我希望将这个结构传递给C中的管道并绕过一系列进程。当我在每个进程中更改count的值时,它会被正确更改。我的问题在于动态数组。
我正在分配数组:
mystruct_t x;
x.arr = malloc( howManyItemsDoINeedToStore * sizeof( int ) );
每个进程都应该从管道中读取,对该数组执行某些操作,然后将其写入另一个管道。戒指设置正确;那里没问题。我的问题是除了第一个进程之外的所有进程都没有获得正确的数组副本。我在第一个过程中将所有值初始化为10,例如10;但是,它们在随后的中都显示为0。
for( j = 0; j < howManyItemsDoINeedToStore; j++ ){
x.arr[j] = 10;
}
日志:
Initally: 10 10 10 10 10
After Proc 1: 9 10 10 10 15
After Proc 2: 0 0 0 0 0
After Proc 3: 0 0 0 0 0
After Proc 4: 0 0 0 0 0
After Proc 5: 0 0 0 0 0
After Proc 1: 9 10 10 10 15
After Proc 2: 0 0 0 0 0
After Proc 3: 0 0 0 0 0
After Proc 4: 0 0 0 0 0
After Proc 5: 0 0 0 0 0
现在,如果我改变我的代码,比如说,
struct mystruct {
int count;
int arr[10];
} mystruct_t;
一切都正确地传递到管道上,没问题。我在C:
中使用read
和write
write( STDOUT_FILENO, &x, sizeof( mystruct_t ) );
read( STDIN_FILENO, &x, sizeof( mystruct_t ) );
答案 0 :(得分:1)
你只是在编写结构。如果你想传递整数数组,你也必须将它写入管道。这就是你的第二个选项正常工作的原因,因为数组被指定为结构的一部分。
答案 1 :(得分:1)
在动态情况下,你的struct不包含数组本身,只是指向它的指针。 (如果你检查sizeof(mystruct_t),你会发现它只能包含一个int和一个指针)。
你不能(有意义地)将指针从一个进程写入另一个进程。
如果要复制可变大小的数组,则必须执行2次写操作:第一次写入mystruct.count,第二次写入int数组。
答案 2 :(得分:1)
当你分配你的动态数组时,malloc函数会返回一个指向你结构中不存在的内存空间的指针。看看这个例子:
0x0000000F int count
0x00000014 >> pointer to your array elsewhere 0x000000F0
0x000000F0 your array is here
您可以使用众所周知的数据填充结构来演示它。
struct mystruct{
int count;
int *arr;
char pad [5];
}mystruct_t;
mystruct_t x;
x.pad={0x5b,0x5C,0x5D,0x5E,0x5F};