Search code examples
ctermiosunistd.h

How to Pass a Character Array to a Function Expecting a void* Pointer?


I'm using the termios.h and unistd.h library to read from a serial port via the read(2) function

ssize_t read(int fd, void *buf, size_t count);

The following code works just fine calling the read function:

char read_buf [256];

int n = read(serial_port, &read_buf, sizeof(read_buf));

Now I'm trying to create a function (readSerial) that calls read() and passes it a pointer to read(). I hardcoded "256" for troubleshooting purposes.

void readSerial(char* msg) {
    int num_bytes;

    num_bytes = read(serial_port, &msg, 256);
}

void main(void) {

char serial_rmsg[256] = {0};

readSerial(serial_rmsg);
printf(serial_rmsg , "%s");
}

I can't figure out to how pass a character array into readSerial such that the void *buf argument of read(2) will accept it.

I tried the above code and read() won't write characters to the address I've provided at &msg.


Solution

  • You originally passed a pointer to an array. But it's equally valid to pass a pointer to an array's element. These both point to the same place. They have different types, but it doesn't matter since we're (implicitly) casting the pointer to a void *.

    And it's why you could have used the following initially:

    char read_buf[256];
    
    int n = read( serial_port, &( read_buf[0] ), sizeof( read_buf ) );
    

    An array used as a pointer degenerates into a pointer to its first element, so that can also be written as follows:

    char read_buf[256];
    
    int n = read( serial_port, read_buf, sizeof( read_buf ) );
    

    And that's exactly what you are doing when you call readSerial.

    readSerial( serial_rmsg, sizeof( serial_rmsg ) )
    

    is short for

    readSerial( &( serial_rmsg[0] ), sizeof( serial_rmsg ) )
    

    In other words, you're already passing a pointer. And so your function should simply look like this:

    void readSerial( char* msg, size_t n ) {
       ...
       num_bytes = read( serial_port, msg, n );
       ...
    }