在C语言中通过管道读写含动态数组的结构体

3

我有一个结构体,里面包含一个动态数组:

struct mystruct {
 int count;
 int *arr;
} mystruct_t;

我希望能够在C语言中通过管道将该结构体传递,并在进程环上循环。当我在每个进程中更改count的值时,它被正确地更改。我的问题出现在动态数组中。

我是这样分配数组的:

mystruct_t x;
x.arr = malloc( howManyItemsDoINeedToStore * sizeof( int ) );

每个进程都应该从管道中读取数据,对数组进行处理,然后将其写入另一个管道。环状结构已正确设置,没有问题。我的问题是,除了第一个进程外,所有进程都没有得到正确的数组副本。我在第一个进程中将所有值初始化为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语言中的readwrite函数:

write( STDOUT_FILENO, &x, sizeof( mystruct_t ) );
read( STDIN_FILENO, &x, sizeof( mystruct_t ) );
3个回答

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};

1
你只是在编写结构体。如果你想传递整数数组,你也必须将其写入管道中。这就是为什么你的第二个选项有效,因为数组被指定为结构体的一部分。

1
在动态情况下,您的结构体并不包含数组本身,而仅包含指向它的指针。(如果您检查 sizeof(mystruct_t),您会发现它只足够容纳一个 int 和一个指针)。
您不能(有意义地)将一个进程中的指针写入另一个进程中。
如果您想复制一个变量大小的数组,您需要进行两次写操作:第一次写入 mystruct.count,第二次写入 int 数组。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接