【问题标题】:Updating the string using function in c使用c中的函数更新字符串
【发布时间】:2021-11-12 20:22:11
【问题描述】:

我编写了以下 c 代码来更新 char 数组 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;
}

限制是我们不能使用任何其他库。那么如何解决这个问题

【问题讨论】:

  • buff = word -> strcpy(buf, word)。目前您只修改本地参数。
  • @mediocrevegetable1 但这需要 string.h
  • 制作自己的strcpy 函数非常简单。您只需要在其位置放置一个for 循环并逐个字符地将word 复制到buff
  • buff[0] = word[0]; buf[1] = word[1]; 等。循环执行。
  • @kaylum 明白了,

标签: arrays c c-strings string-literals strcpy


【解决方案1】:

在函数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;
}

【讨论】:

    【解决方案2】:

    由于你不能使用任何库函数,只需逐个单元格进行反复制,更改

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

    【讨论】:

      【解决方案3】:

      buff 是函数的局部变量。它被初始化为指向mainrb 数组的第一个元素,但更改为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(rb, "HII_O");。我认为这里我们需要使用strcpy(buff, "HII_O");。因为rb 在这个函数中没有任何作用域。
      • @VishnuCS 那是一个错字。现已更正。谢谢。
      猜你喜欢
      • 2021-12-14
      • 2021-09-24
      • 2014-10-29
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 2019-04-20
      相关资源
      最近更新 更多