2014-03-06 35 views
0

这是我的主:如何更改char指针的值?

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

,我需要改变这个函数的w1[]值:

ChangeTheWord(char *Str) 
{ 

    ... 

} 
+3

'w1'是一个数组,而不是一个指针。你想改变数组的_contents_吗? –

+1

'strcpy(Str,“Rome”);' – ouah

+0

@CharlesBailey是的,我想改变arry的内容。 – benhi

回答

3
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答案太

+0

为什么投票?,长度“巴黎”==长度“德里” –

+0

@Chauhan抱歉,我不明白这里提到的长度有什么重要意义? –

+1

,因为'w1 []'的大小与“巴黎”的大小相等,等于“德里”的大小 - 您无法指定“新德里”,它会导致未定义的行为 –

2

你可以简单地访问每个指标,并与所需的值替换.. 一个制造改变例如...

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

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

+0

否该函数是“ void ChangeTheWord(char * Str)“ – benhi

+0

@benhi yes'ChangeTheWord'不返回,但改变你的数组。你将数组'w1'的地址传递给你的函数。 –

+0

在'C'中写'void'是多余的......我想我有这个习惯会让事情变得更加清晰......参数的名字也没有关系...... – HadeS

0

这是你如何做到的。

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

} 
+0

好吧,第二个......? – benhi

+0

你的意思是第二个字符? –

7

所有的答案至今是正确的,但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字节。所以你必须自己照顾。

1

实际上,您可以使用指针表示法在循环中更改每个索引的值。喜欢的东西...

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