Updating the string using function in c

Viewed 93

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

3 Answers

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;
}

buff is a local variable to the function. It is initialized to point to the first element of the rb array in main but changes to buff will not change the rb array. So

buff = word;

makes buff point to the string literal "HII_O" but there is no change to the rb array.

The normal solution would be

void update(char* buff){
    strcpy(buff, "HII_O");
}

However, you write ...

The restriction is we can't use any other library.

Well, in order to set a fixed value like your code does, you don't need any library function.

You don't any need other variables, string literals, etc.

Just simple character assignments like:

void update(char* buff){
    buff[0] = 'H';
    buff[1] = 'I';
    buff[2] = 'I';
    buff[3] = '_';
    buff[4] = 'O';
    buff[5] = '\0';
}

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

As you cannot use any library function, just do de copying cell by cell, change

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

(you cannot assign arrays as a whole in C) into:

void update(char *buff) {
    char *word = "HII_O";
    int index;
    /* copy characters, one by one, until character is '\0' */
    for (index = 0; word[index] != '\0'; index = index + 1) {
        buff[index] = word[index];
    }
    /* index ended pointing to the next character, so we can
     * do the next assignment. */
    buff[index] = '\0'; /* ...and copy also the '\0' */
}
Related