Need explanation about what the writer is trying to do here. Why cannot I use Single dimension array instead od 2d array?
char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];
Program snippet:
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;
}
explain the meaning of two lines below
The line
char writemessages[2][20]={"Hi", "Hello"};
defines an array of characters having 2 rows of 20 columns and initializes it, because of the null character to end the strings the array can contains 2 strings having up to 19 characters excluding the null character.
The initialization makes the first string to be 'H'
'i'
then the null char, and the second 'H'
'e'
'l'
'l'
'o'
then the null char
This is a short way equivalent to :
char writemessages[2][20]={ { 'H', 'i', 0 }, { 'H', 'e', 'l', 'l', 'o', 0 }};
or
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 }
};
The line
char readmessage[20];
defines an array of size 20 so allowing up to 19 characters more the null character.
Why cannot I use Single dimension array instead od 2d array?
this is just a choice to group them in a 2 dimensional array, you can also use single dimension arrays :
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));
Note the code send always 20 characters, changing the definitions to have
char writemessage1[] = "Hi";
char writemessage1[] = "Hello";
write(pipefds[1], writemessage1, sizeof(writemessage1));
sends 3 characters and write(pipefds[1], writemessage2, sizeof(writemessage2));
sends 6 characters because of the size of the arrays (they are automatically sized and initialized to contain the ending null character)
probably
printf("Writing to pipe - Message 2 is %s\n", writemessages[0]); write(pipefds[1], writemessages[1], sizeof(writemessages[0]));
must be
printf("Writing to pipe - Message 2 is %s\n", writemessages[1]); write(pipefds[1], writemessages[1], sizeof(writemessages[1]));
to send "Hello" rather than again "Hi"