Home > OS >  Returning result via pointer to array
Returning result via pointer to array

Time:11-11

I want to return the result of a function through the pointer *address, given as parameter. My code below prints this output:

Result:

But I was expecting:

Result: 123456

Why isn't it working as expected?

#include <stdio.h>

static void get_address(char *address) {
    address = "123456";
}


int main(int argc, const char * argv[]) {

    char address[34];
    get_address(address);
    printf("Result: %s\n",address);

    return 0;
}

CodePudding user response:

'address' in get_address gets a copy of the address of the start of the array address in main(). get_address changes that local pointer to the address of the local string "123456" and then does nothing with it. What you meant to do is probably the following:

    static void get_address(char* address) {
        const char str[] = "123456";
        strcpy_s(address, strlen(str) 1, str);
    }

Here strcpy_s is the safe version of strcpy and is used to copy the contents of the local str char-array to the memory location specified by address in get_address.

CodePudding user response:

#include <stdio.h>

static void get_address(char *address) {
     //Attention here
     // use the reference operator
     // (in your code you were affecting to the address of the variable not it's content)
    *address = "123456";
}
  • Related