-3

I am trying to assign new value for my char s[128] array. But after performing function, the address of the s doesn't change. On the other hand the function works just fine for the ints.


void myscanf(const char *type, void *var){
    char buffer[128];
    memset(buffer,0,sizeof(buffer));
    int size = read(0, buffer, 128);
    if(strcmp(type, "%d") == 0){
        int *d = (int*)var;
        *d = buffer[0] - '0';   
    }
    else if(strcmp(type,"%s") == 0){
        char* str = (char*) var;
        str = buffer;
    }
}

int main(){
    int d;
    char s[128];
    myscanf("%s", s);

    return 0;
}
Jakub Balicki
  • 180
  • 1
  • 11
  • 1
    C uses pass-by-value, functions receive copies of the arguments – M.M Nov 27 '19 at 23:36
  • 1
    Arrays are not pointers. You cannot reassign arrays – UnholySheep Nov 27 '19 at 23:36
  • Possible duplicate of [Update global variable in C via reference by parameter](https://stackoverflow.com/questions/39715740/update-global-variable-in-c-via-reference-by-parameter). However, you don't really want to return a pointer to the local array back to the main function. – vgru Nov 27 '19 at 23:37
  • Why does it work on int, but doesn't on this array? – Jakub Balicki Nov 27 '19 at 23:46
  • Is it possible to achieve this in this style? – Jakub Balicki Nov 27 '19 at 23:47
  • 1
    @JakubBalicki The int version uses `*` (in `*d`) to store through the pointer. `char *str = var; str = buffer;` just locally stores an argument and then overwrites that local variable with a local address. Playing around with postal addresses without sending your letters won't have any effect outside of your home. – Petr Skocik Nov 27 '19 at 23:54
  • Oh, I see, thanks again @PSkocik! – Jakub Balicki Nov 27 '19 at 23:56

1 Answers1

1

char* str = var; (cast not needed) converts the var void pointer to a locally stored char * pointer and then overwrites that value with the address of &buffer[0] (the first element of the buffer char array, decay implicit).

This has no observable effect (and can be optimized out completely).

What you likely want is to copy characters from your buffer through the var/str pointer and then \0-terminate:

char* str = var;
memcpy(str, buffer, size);
str[size]='\0';

Note that read should have requested 127 bytes (or myscanf caller should have provided 128+1 bytes of space) and that you should have checked the read call for possible failure.

The memset call is unnecessary.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142