Search code examples
csocketsstrncpy

Explanation of the following strncpy call


I am currently reading a book (Linux Socket Programming - BY EXAMPLE) and on page 45 The Author uses a strange use(call) of strncpy and I can not understand why it is also working:

strncpy(  adr_unix.sun_path,
          pth_unix,
          sizeof( adr_unix.sun_path ) - 1 ) [sizeof adr_unix.sun_path - 1] = 0;

I was expecting that it should be like this:

strncpy(    adr_unix.sun_path,
            pth_unix,
            sizeof( adr_unix.sun_path ) - 1 );

adr_unix.sun_path[sizeof adr_unix.sun_path - 1] = 0;

What kind of code use is here in the third argument of strncpy?:

sizeof( adr_unix.sun_path - 1 ) ) [sizeof adr_unix.sun_path - 1] = 0;

Solution

  • Pay attention that strncpy call terminates here

    strncpy(adr_unix.sun_path,
            pth_unix,
            sizeof( adr_unix.sun_path ) - 1 )
    

    So because strncpy returns destination (adr_unix.sun_path) that calls it's equivalent to yours

    strncpy(    adr_unix.sun_path,
            pth_unix,
            sizeof( adr_unix.sun_path ) - 1 );
    
    adr_unix.sun_path[sizeof adr_unix.sun_path - 1] = 0;
    

    and third argument of strncpy call is only sizeof( adr_unix.sun_path) - 1