簡體   English   中英

用C中的指針更改字符串的值

[英]Changing the value of a string with a pointer in C

我試圖通過將字符串的指針傳遞給函數,然后在函數中更改該指針的值來更改字符串t_string的值。

我收到的輸出是原始字符串“ Hello”。

任何幫助將不勝感激:)謝謝!

#include <stdio.h>
#include "string.h"

void editString(char *theString);

int main() {
    char t_string[] = "Hello\n";
    char *s = t_string;
    editString(s);
    printf("The string after: %s", t_string);
    return 0;
}

void editString(char *theString){
    theString = "Good Bye\n";
}

在C語言中,參數按值傳遞。 您正在做的是更改局部變量theString的值以指向字符串文字。 局部變量的變化不會反映在調用函數中。

要更改theString指向的內容,請使用strcpy 這將遵循theString指向的內容(即main的數組)。 但是請注意,數組的大小不足以容納新的字符串,因此,如果這樣做,您將在數組的末尾進行寫操作並調用未定義的行為。 因此,您需要使數組足夠大以容納任一字符串。

int main() {
    char t_string[20] = "Hello\n";   // enlarge array to hold either string
    char *s = t_string;
    editString(s);
    printf("The string after: %s", t_string);
    return 0;
}

void editString(char *theString){
    strcpy(theString, "Good Bye\n");   // use strcpy
}

數組指示符是不可修改的左值。 因此,您不能以這種方式更改數組。

在此聲明中

char *s = t_string;

創建了一個名為s的新對象,該對象由數組t_string的第一個字符的地址初始化。

在這次通話中

editString(s);

將創建分配給函數參數的參數值的副本。

您可以通過以下方式想象函數定義及其調用

editString(s);

//...

void editString(/*char *theString*/){
    char *theString = s; 
    theString = "Good Bye\n";
}

因此,即使參數s也不會被函數更改。 首先是由存儲在參數s的值初始化的局部變量theString ,然后由字符串文字"Good Bye\\n"的第一個字符的地址重新分配此局部變量。

t_string未更改數組t_string或main中定義的指針s

如果要更改數組,則必須單獨分配其字符,例如,使用在標題<string.h>聲明的標准字符串函數strcpy 數組必須具有足夠的大小以容納新的字符串文字。

例如

#include <stdio.h>
#include "string.h"

void editString(char *theString);

int main( void ) 
{
    char t_string[10] = "Hello\n";
    char *s = t_string;
    editString(s);
    printf("The string after: %s", t_string);
    return 0;
}

void editString(char *theString){
    strcpy( theString, "Good Bye\n" );
}

考慮到根據C標准,沒有參數的函數main應該聲明為

int main( void )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM