为什么在函数中使用后不删除char *? [重复]

问题描述 投票:-2回答:2

这个问题在这里已有答案:

看这个

int fun(void) {  
    int x = 3; 
    printf("The address of x in the function is %p", &x); 
    return x; 
} 

int main(void) { 
    int x; 
    x = fun(); 
    printf("\nThe address of x in the main is: %p\n", &x); 
} 

它打印:

The address of x in the function is 6A
The address of x in the main is 4A

这是正确的,因为它们在内存中是不同的变量,但现在看看这个:

char *fun(void){ 
    char *x = "HELLO"; 
    printf("The address of the string in the function is %p",x); 
    return x; 
}

int main(void) { 
    char *x = "HELLO"; 
    printf("\nThe address of the first string in the main is %p\n", x); 
    x = fun(); 
    printf("\nThe address of the string in the main now is %p\n", x); 
} 

现在它打印:

The address of the first string in the main is 6A
The address of the string in the function is 4A 
The address of the string in the main now is 4A

为什么?

这就像函数中的字符串是静态的,因为即使在函数结束后也存在相同的值。

我是初学者,所以如果这不是一个好问题,我真的很抱歉。

c string pointers char
2个回答
2
投票

虽然字符串常量确实是静态的,但您看到的打印值与此无关。

fun里面,x包含一个字符串常量的地址。然后该函数返回该指针的值并存储在main中的x中。所以指针的值是相同的。

在这种情况下,因为指针指向一个字符串常量,该字符串常量在程序的生命周期中可见,如果您要打印字符串,它将正确打印。但即使指针无效,指针本身的值仍然是相同的。在这种情况下,您将无法安全地取消引用它,但值仍然是相同的。

以下程序与第二个程序的作用相同,但使用不同的指针类型:

int *fun(void){
    int a = 5;
    int *x = &a;
    printf("The address of a in the function is %p",x);
    return x;
}
int main(void){
    int *x=fun();
    printf("\nThe address in main now is %p\n",x);
}

输出:

The address of a in the function is 0x7ffe4385fb04
The address in main now is 0x7ffe4385fb04

与您的程序一样,这将打印返回的指针的值。该指针不再指向某个地方有效,因此尝试在*x中使用main()会调用未定义的行为,但打印指针是有效的。


2
投票

中的所有常量字符串都是只读字符数组。

在函数中,你使x指向一个这样的数组的第一个元素。然后你返回那个指针。

在函数外部,您将指针指向变量x(您的main函数),但它仍指向相同的内存(包含来自"HELLO"函数内部的fun的数组的第一个元素)。

你真的打印x的值,而不是变量的地址。

所以你的第二个例子更像是

int fun(void) {  
    int x = 3; 
    printf("The value of x in the function is %d", x); 
    return x; 
} 

int main(void) { 
    int x; 
    x = fun(); 
    printf("\nThe value of x in the main is: %d\n", x); 
} 

如果您希望两个代码片段相同,则应打印变量x的地址,而不是其值。

© www.soinside.com 2019 - 2024. All rights reserved.