有人可以在实现管道的程序中解释以下两行的含义吗?

时间:2019-06-01 10:09:27

标签: c pipe posix ipc

需要作者在这里做些什么的解释。 为什么不能使用一维数组而不是od 2d数组?

char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];

程序段:

   int main() {
   int pipefds[2];
   int returnstatus;
   char writemessages[2][20]={"Hi", "Hello"}; //why can't i use singlr char array
   char readmessage[20];
   returnstatus = pipe(pipefds);

   if (returnstatus == -1) {
      printf("Unable to create pipe\n");
      return 1;
   }

   printf("Writing to pipe - Message 1 is %s\n", writemessages[0]);
   write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
   read(pipefds[0], readmessage, sizeof(readmessage));
   printf("Reading from pipe – Message 1 is %s\n", readmessage);
   printf("Writing to pipe - Message 2 is %s\n", writemessages[0]);
   write(pipefds[1], writemessages[1], sizeof(writemessages[0]));
   read(pipefds[0], readmessage, sizeof(readmessage));
   printf("Reading from pipe – Message 2 is %s\n", readmessage);
   return 0;
}

1 个答案:

答案 0 :(得分:0)

  

解释下面两行的含义

char writemessages[2][20]={"Hi", "Hello"};

定义一个具有2行20列的字符数组并将其初始化,因为空字符将字符串结尾,所以该数组可以包含2个字符串,其中最多包含19个字符(不包括空字符)。

初始化使第一个字符串为'H' 'i',然后为空字符,第二个字符串为'H' 'e' 'l' 'l' { {1}},然后为空字符

这是等效于:

的简短方式
'o'

char writemessages[2][20]={ { 'H', 'i', 0 }, { 'H', 'e', 'l', 'l', 'o', 0 }};

char writemessages[2][20]= {
   { 'H', 'i', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
   { 'H', 'e', 'l', 'l', 'o', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

定义大小为20的数组,以便允许空字符最多增加19个字符。

  

为什么我不能使用一维数组代替od 2d数组?

这只是将它们分组为二维数组的一种选择,您也可以使用一维数组:

char readmessage[20];

请注意,代码始终发送20个字符,将定义更改为具有

 char writemessage1[20] = "Hi";
 char writemessage1[20] = "Hello";

 printf("Writing to pipe - Message 1 is %s\n", writemessage1);
 write(pipefds[1], writemessage1, sizeof(writemessage1));
 ...
 printf("Writing to pipe - Message 2 is %s\n", writemessage2);
 write(pipefds[1], writemessage2, sizeof(writemessage2));

char writemessage1[] = "Hi"; char writemessage1[] = "Hello"; 发送3个字符,write(pipefds[1], writemessage1, sizeof(writemessage1));发送6个字符,这是由于数组的大小(它们会自动调整大小并初始化为包含结尾的空字符)


可能

write(pipefds[1], writemessage2, sizeof(writemessage2));

必须

printf("Writing to pipe - Message 2 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[1], sizeof(writemessages[0]));

发送“ Hello”而不是“ Hi”