【问题标题】:How to change the value of char pointer?如何更改char指针的值?
【发布时间】:2014-03-06 09:18:59
【问题描述】:

这是我的主要内容:

int main(void)
{
    char w1[] = "Paris";
    ChangeTheWord(w1);
    printf("The new word is: %s",w1);
    return0;
}

我需要在这个函数中更改w1[] 的值:

ChangeTheWord(char *Str)
{

     ...

}

【问题讨论】:

  • w1 是一个数组,而不是一个指针。是否要更改数组的内容
  • strcpy(Str, "Rome");
  • @CharlesBailey 是的,我想更改 arry 的内容。

标签: c arrays pointers


【解决方案1】:

到目前为止所有答案都是正确的,但 IMO 不完整。

在 C 中处理字符串时,避免缓冲区溢出很重要。

如果ChangeTheWord() 尝试将单词更改为过长的单词,您的程序会崩溃(或至少显示未定义的行为)。

最好这样做:

#include <stdio.h>
#include <stddef.h>

void ChangeTheWord(char *str, size_t maxlen)
{
    strncpy(str, "A too long word", maxlen-1);
    str[maxlen] = '\0';
}

int main(void)
{
    char w1[] = "Paris";
    ChangeTheWord(w1, sizeof w1);
    printf("The new word is: %s",w1);
    return 0;
}

使用此解决方案,函数会被告知允许访问的内存大小。

请注意,strncpy() 并不像乍一看会怀疑的那样工作:如果字符串太长,则不会写入 NUL 字节。所以你必须自己照顾。

【讨论】:

    【解决方案2】:
    int main()
    {
        char w1[]="Paris";
        changeWord(w1);      // this means address of w1[0] i.e &w[0]
        printf("The new word is %s",w1);
        return 0;
    
    }
    void changeWord(char *str) 
    {
        str[0]='D';         //here str have same address as w1 so whatever you did with str will be refected in main(). 
        str[1]='e';
        str[2]='l';
        str[3]='h';
        str[4]='i';
    }
    

    阅读this也回答

    【讨论】:

    • 为什么投反对票?,“Paris”的长度 == “Delhi”的长度
    • @Chauhan 抱歉,我不明白这里提到长度有什么意义?
    • 因为 w1[] 的大小与 sizeof "Paris" 的大小相同,即等于 "Delhi" 的大小 -- 你不能指定 "New Delhi" 这将导致未定义的行为
    • @GrijeshChauhan 好的,我明白你的意思很抱歉,我已经编辑了答案
    【解决方案3】:

    您可以简单地访问每个索引并替换为所需的值.. 例如进行了一项更改...

    void ChangeTheWord(char *w1)
    {
         w1[0] = 'w';
         //....... Other code as required
    }
    

    现在,当您尝试打印main() 中的字符串时,输出将是Waris

    【讨论】:

    • NO 函数是“void ChangeTheWord(char *Str)”
    • @benhi yes ChangeTheWord 不会返回但会更改您的数组。您正在将数组地址 w1 传递给您的函数。
    • C 中写void 是多余的......我想我有这个习惯让我更清楚......参数的名称也无关紧要......
    • @HadeS "在C 中写void 是多余的" 在什么方面是多余的?
    • @benhi 从外观上看,参数名称是w1 还是Str 并不重要。
    【解决方案4】:

    你可以这样做。

    ChangeTheWord(char *Str)
    {
            // changes the first character with 'x'
            *str = 'x';
    
    }
    

    【讨论】:

    • 你的意思是第二个字符吗?
    【解决方案5】:

    您实际上可以在循环中使用指针表示法更改每个索引的值。比如……

    int length = strlen(str);              // should give length of the array
    
    for (i = 0; i < length; i++)
        *(str + i) = something;
    

    或者您应该能够对索引进行硬编码

       *(str + 0) = 'x';
       *(str + 1) = 'y';
    

    或使用数组表示法

    str[0] = 'x';
    str[1] = 'y';
    

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-12
      相关资源
      最近更新 更多