Can anyone explain to me in a very simple way the meaning of these lines of code.
typedef int pipe_t[2];
pipe_t *piped;
int L;
L = atoi(argv[2]);
piped = (pipe_t *) malloc (L*sizeof(pipe_t));
Can anyone explain to me in a very simple way the meaning of these lines of code.
typedef int pipe_t[2];
pipe_t *piped;
int L;
L = atoi(argv[2]);
piped = (pipe_t *) malloc (L*sizeof(pipe_t));
pipe_t
is "array of 2 ints"piped
is a pointer to such arrays.L
is an integer, assigned from the command linepiped
is assigned to point to a block of memory large enough for L
arrays of the type above.For this typedef, you can read the declaration from right to left, so in
typedef int pipe_t[2];
you have
[2]
says it is an array of 2. Positions [0] and [1]pipe_t
is the variable (type) nameint
says pipe_t[2]
is an array of 2 int
typedef
says that it is, in fact, a type — an alias for a user-defined type representing an array of 2 int
.Run this program
#include<stdio.h>
int main(int argc, char** argv)
{
typedef int pipe_t[2];
printf("{typedef int pipe_t[2]} sizeof(pipe)_t is %d\n",
sizeof(pipe_t));
pipe_t test;
test[1] = 2;
test[0] = 1;
printf("pair: [%d,%d]\n", test[0], test[1]);
// with no typedef...
int (*another)[2];
another = &test;
(*another[0]) = 3;
(*another)[1] = 4;
printf("{another} pair: [%d,%d]\n", (*another)[0], (*another)[1]);
pipe_t* piped= &test;
printf("{Using pointer} pair: [%d,%d]\n", (*piped)[0], (*piped)[1]);
return 0;
};
And you see
{typedef int pipe_t[2]} sizeof(pipe)_t is 8
pair: [1,2]
{another} pair: [3,4]
{Using pointer} pair: [3,4]
And you see that pipe_t
has a size of 8 bytes, corresponding to 2 int
's in x86 mode. And you can declare test
as pipe_t
and use it as an array of int
. And the pointer works the same way
And I added the code to be used without such typedef, so we see that using a typedef makes it a bit cleaner to read.