This question already has answers here:
Closed 7 months ago.
Function returning address of local variable error in C
(3个答案)
显示本地函数中指针所引用的值对我有意义,在主函数中调用此本地函数,指针所引用的值已更改。
#include<stdio.h>

char *getAnotherString(){

    char target[] = "Hi, ComplicatedPhenomenon";
    char *ptrToTarget = target;

    printf("ptrToTarget                 = %p\n", ptrToTarget);
    printf("ptrToTarget                 = %s\n", ptrToTarget);
    return ptrToTarget;

}

int main(){
    char *ptrToTarget = NULL;
    ptrToTarget = getAnotherString();
    printf("ptrToTarget                 = %p\n", ptrToTarget);
    printf("ptrToTarget                 = %s\n", ptrToTarget);

    return 0;
}


我希望输出像
ptrToTarget                 = 0x7ffeeed1c950
ptrToTarget                 = Hi, ComplicatedPhenomenon
ptrToTarget                 = 0x7ffeeed1c950
ptrToTarget                 = Hi, ComplicatedPhenomenon

实际输出是
ptrToTarget                 = 0x7ffeeed1c950
ptrToTarget                 = Hi, ComplicatedPhenomenon
ptrToTarget                 = 0x7ffeeed1c950
ptrToTarget                 = Hi, ComplicatedP

最佳答案

char target[] = "Hi, ComplicatedPhenomenon";

是一个本地字符数组。这意味着,一旦函数结束,它将变为无效,以后不应再使用它。这样做将调用未定义的行为,这意味着输出可以是任何内容。
可以通过使用malloc或使用static数组动态分配内存来解决此问题。

09-10 05:33
查看更多