4

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 =)

Ollie
  • 473
  • 3
  • 7
  • 19

1 Answers1

14

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);
MByD
  • 135,866
  • 28
  • 264
  • 277
  • yes that worked thank you! :) so what does strcpy do that the = doesn't? I think I still have 1/2 my head floating around Java and C# as that is what I have done in the past!! lol – Ollie May 06 '12 at 06:20
  • 1
    `strcpy` copies a c string from one buffer to another, but a safer function is `strncpy`, take a look here:http://www.cplusplus.com/reference/clibrary/cstring/strncpy/ – MByD May 06 '12 at 06:21
  • thank you for helping me understand! :) very good and complete answer! – Ollie May 06 '12 at 06:25
  • @MByd `strncpy` is [**not** a safer version of `strcpy`](https://stackoverflow.com/q/869883/694733). – user694733 May 29 '17 at 10:12