samedi 2 juillet 2016

Manipulating char arrays in C - Empty pointers?

I'm coming from a long experience from Java, so this makes no sense what so ever to me right now. I have this:

#include <stdio.h>
#include <string.h>
#include <sys/utsname.h>

#include "uname.h"

int main(void) {

    char *var; 
    getKernelVersion(&var);

    printf("%sn", var);
    return 0;

}

int getKernelVersion(char **ver) {

    struct utsname buf;
    int errno;
    errno = uname(&buf);
    strcpy(*ver, buf.release);

    return errno;
}

The first line I'm confused about is char *var, it is a pointer that points to ... ehm .. nowhere? Where does it point to?

The next thing that is confusing is the double pointer in the function arguments char **ver. It creates a pointer that points to ... nothing?!

Thenn, strcpy(*ver, buf.release) somehow magically copies buf.release, which is this

struct utsname {
    char sysname[];    /* Operating system name (e.g., "Linux") */
    char nodename[];   /* Name within "some implementation-defined
                                     network" */
    char release[];    /* Operating system release (e.g., "2.6.28") */
    char version[];    /* Operating system version */
    char machine[];    /* Hardware identifier */
    #ifdef _GNU_SOURCE
        char domainname[]; /* NIS or YP domain name */
    #endif
};

Into the empty pointer *var somehow, and then i print out var which now magically contains the value of buf.release.

How come I did not have to allocate memory for char *var? How does it hold the string I need? What is life right now?

Aucun commentaire:

Enregistrer un commentaire