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

1 Answer 1

15

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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
strcpy copies a c string from one buffer to another, but a safer function is strncpy, take a look here:cplusplus.com/reference/clibrary/cstring/strncpy
thank you for helping me understand! :) very good and complete answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.