Home > Blockchain >  C pass by reference without ampersand [duplicate]
C pass by reference without ampersand [duplicate]

Time:09-17

I was studying a socket tutorial in C, and I came across this:

char buffer[256];
bzero(buffer, 256);
n = read(newsockfd, buffer, 255);

However, as far I know, shouldn't the buffer variable be passed by reference (using &) to bzero and read functions? As well, the man pages for bzero and read specify that these arguments are pointers. Am I missing something?

CodePudding user response:

The variable buffer is declared as having an array type

char buffer[256];

Array designators used in expressions are implicitly converted (with rare exceptions) to pointers to their first elements.

The function bzero changes elements of the array buffer So in fact all elements of the array are passed to the function by reference through the pointer to the first element of the array due to the mentioned above implicit conversion

bzero(buffer, 256);

As a result, the function can access and change any element of the array using the passed pointer and the pointer arithmetic.

CodePudding user response:

C has no pass by reference. You cannot pass things by reference in C. You can only pass by value.

The value passed here is a pointer to the first object in buffer. That is all either bzero or read need because an array always occupies a contiguous chunk of memory.

CodePudding user response:

When you call functions with an array,

char buffer[256];
bzero(buffer, sizeof buffer);

the array decays into a pointer:

void bzero(char *buffer, size_t len) {
    //...
}

If you on the other hand take the address of the array:

foo(&buffer);

A matching function would have to have a signature like:

void foo(char(*buffer)[256]) {
    // ...
}

The latter is pretty uncommon since it'd only accept arrays of a certain size.

  • Related