在C语言中使用函数更新字符串

3
我已经编写了以下C代码来更新字符数组rb,但它打印出垃圾值。
#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;
}

限制条件是我们不能使用任何其他库。那么该怎么解决呢?

6
目前你只是修改了局部参数,应该改为将word复制到buf中,即:strcpy(buf, word) - mediocrevegetable1
3
制作自己的strcpy函数非常简单。您只需要在其位置放置一个for循环,并逐个字符将word复制到buff中。 - mediocrevegetable1
2
在一个循环中执行以下操作:buff[0] = word[0]; buf[1] = word[1]; 等等。 - kaylum
@ancadancad 使用string.h有什么问题吗? - Jabberwocky
@Jabberwocky,我解决问题时并不允许使用这个(或任何其他)库。 - ancad ancad
显示剩余2条评论
3个回答

0

在函数update中,参数buff是函数的局部变量,在退出函数后不再有效。

你可以把函数调用看做下面这样

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

正如您所看到的,原始数组并未更改。

首先,指针buff被初始化为源数组rb的第一个元素的地址。

    char *buff = rb;

然后这个指针被重新赋值为本地字符数组word的第一个元素的地址。

    buff = word;

你需要做的是使用标准字符串函数 strcpystrncpy 将字符串字面值 "HII_O" 的字符复制到源数组 rb 中。

例如:

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

0

buff是该函数的局部变量。它被初始化为指向main函数中rb数组的第一个元素,但对buff的更改不会改变rb数组。因此,

buff = word;

使buff指向字符串字面值"HII_O",但是rb数组没有改变。 正常的解决方案是:
void update(char* buff){
    strcpy(buff, "HII_O");
}

然而,你写的代码...

限制是我们不能使用任何其他库。

好吧,为了像你的代码一样设置一个固定值,你不需要任何库函数。

你不需要其他变量、字符串字面量等。

只需要简单的字符赋值即可:

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

我认为我们需要使用strcpy(buff, "HII_O");,因为在这个函数中rb没有任何作用域。 - Vishnu CS
1
@VishnuCS 那是打错字,已经更正了。谢谢。 - Support Ukraine

0

由于您无法使用任何库函数,因此只需逐个复制单元格并更改即可。

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

(你不能在C语言中整体赋值数组)

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' */
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接