passing a char array by reference in C

26,344

This line:

*name = "testing"; 

is invalid, as you assign the pointer to "testing" into a char pointed by name. You need to copy the data into the buffer. It should be:

int GetComputerName(char *name, char *ip_address){
    strcpy(name,"testing");
    return 0;
}

or even better (to avoid overflows):

int GetComputerName(char *name, size_t buff_len, char *ip_address){
    strncpy(name,"testing", buff_len);
    name[buff_len - 1] = '\0';
    return 0;
}

And call it:

GetComputerName(comp_name, sizeof(comp_name), serverIP);
Share:
26,344
Ollie
Author by

Ollie

Software Engineer

Updated on August 02, 2022

Comments

  • Ollie
    Ollie almost 2 years

    Hi I really can't get my head around this. I'm basically trying to return a char array from a function by passing the output array in as a parameter. Here is what I have so far:

    The function:

    int GetComputerName(char *name, char *ip_address){
        *name = "testing";
        return 0;
    }
    

    And calling it:

    char comp_name[50];
    GetComputerName(&comp_name, serverIP);
    printf("\n\n name: %s\n\n", comp_name);
    

    I have tried switching and swapping the * and & to see what will work and have read up on pointers and stuff yet what I think should be happening an what actually does happen is two very different things and now I think I have confused myself more than when I started!! lol

    Can someone please help me out and explain what the correct way of doing this is?!

    Thanks in advance =)