Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何更改char指针的值?_C_Arrays_Pointers - Fatal编程技术网

如何更改char指针的值?

如何更改char指针的值?,c,arrays,pointers,C,Arrays,Pointers,这是我的主要观点: int main(void) { char w1[] = "Paris"; ChangeTheWord(w1); printf("The new word is: %s",w1); return0; } 我需要更改此函数中w1[]的值: ChangeTheWord(char *Str) { ... } 您只需访问每个索引并替换为所需的值即可。。 做了一个改变,例如 void ChangeTheWord(char *w1) {

这是我的主要观点:

int main(void)
{
    char w1[] = "Paris";
    ChangeTheWord(w1);
    printf("The new word is: %s",w1);
    return0;
}
我需要更改此函数中
w1[]
的值:

ChangeTheWord(char *Str)
{

     ...

}

您只需访问每个索引并替换为所需的值即可。。 做了一个改变,例如

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

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

这就是您可以做到的方法

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

}

阅读答案

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

在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;
}
#包括
#包括
无效更改字(字符*str,大小\u t最大值)
{
strncpy(str,“太长的单词”,maxlen-1);
str[maxlen]='\0';
}
内部主(空)
{
字符w1[]=“巴黎”;
更改单词(w1,w1的大小);
printf(“新词是:%s”,w1);
返回0;
}
使用此解决方案,函数将被告知允许访问的内存大小


请注意,
strncpy()
并不像人们第一眼看到的那样工作:如果字符串太长,就不会写入NUL字节。因此,您必须自己小心。

实际上,您可以使用循环中的指针符号更改每个索引的值。类似于

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

w1
是一个数组,而不是指针。是否要更改数组的内容?
strcpy(Str,“Rome”)
@CharlesBailey yes我想更改arry的内容。NO的可能重复函数是“void ChangeTheWord(char*Str)”@benhi yes
ChangeTheWord
不会返回,但会在适当的位置更改数组。您正在将数组的地址
w1
传递给函数。在
C
中写入
void
是多余的。。。我想我有这个习惯,让事情变得更清楚。。。另外,参数的名称也不重要…@HadeS“在
C
中写入
void
是冗余的”以何种方式冗余?@benhi从外部来看,参数名称是
w1
还是
Str
都不重要。你是说第二个字符吗?为什么被否决?“Paris”的长度=长度“drih”@Chauhan抱歉,我不明白这里提到长度有什么意义?因为
w1[]
的大小与“巴黎”的大小相同,即等于“德里”的大小-您不能指定“新德里”,这将导致未定义behaviour@GrijeshChauhan好的,我明白你的意思,抱歉,我已经编辑了答案
   *(str + 0) = 'x';
   *(str + 1) = 'y';
str[0] = 'x';
str[1] = 'y';