Search code examples
arrayscc-stringsstring-literalsstrcpy

Updating the string using function in c


I have written following c code to update the char array rb but it is printing garbage value

#include <stdio.h>
void update(char* buff){
    char word[] = "HII_O";
    buff = word;
    return;
}

int main(){
    char rb[6];
    update(rb);
    rb[5] = '\0';
    printf("[%s]\n",rb);
    return 0;
}

The restriction is we can't use any other library. So how to solve this


Solution

  • Within the function update the parameter buff is a local variable of the function that will not be alive after exiting the function.

    You can imagine the function call the following way

    update( rb );
    //...
    void update( /*char* buff*/){
        char *buff = rb;
        char word[] = "HII_O";
        buff = word;
        return;
    }
    

    As you see the original array was not changed.

    That is at first the pointer buff was initialized by the address of the first element of the source array rb.

        char *buff = rb;
    

    and then this pointer was reassigned with the address of the first element of the local character array word

        buff = word;
    

    What you need is to copy characters of the string literal "HII_O" into the source array rb using standard string function strcpy or strncpy.

    For example

    #include <string.h>
    #include <stdio.h>
    
    void update(char* buff){
        strcpy( buff, "HII_O" );
    }
    
    int main(){
        char rb[6];
        update(rb);
        printf("[%s]\n",rb);
        return 0;
    }