[英]How to change the value of char pointer?
這是我的主要:
int main(void)
{
char w1[] = "Paris";
ChangeTheWord(w1);
printf("The new word is: %s",w1);
return0;
}
我需要在此函數中更改w1[]
的值:
ChangeTheWord(char *Str)
{
...
}
到目前為止,所有答案都是正確的,但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字節。 因此,您必須自己保重。
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';
}
也閱讀此答案
您可以簡單地訪問每個索引並替換為所需的值。例如,進行了一次更改...
void ChangeTheWord(char *w1)
{
w1[0] = 'w';
//....... Other code as required
}
現在,當您嘗試在main()
打印字符串時,輸出將為Waris
。
您實際上可以在循環中使用指針符號更改每個索引的值。 就像是...
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';
這就是您可以做到的。
ChangeTheWord(char *Str)
{
// changes the first character with 'x'
*str = 'x';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.