我正在编写一个非常简单的字符串反转函数,
void reverse(char *data) {
int length = 0,i;
char *temp,temp1[100];
temp = data;
length = strlen(temp);
printf("length %d\n", length);
for(i=length-1; i>=0; i--) {
temp1[i] = *temp;
printf("data[%d] = %c\n",i,temp1[i]);
printf("%c\n",*temp);
temp++;
}
temp1[length] = '\0';
printf("data %s\n", temp1);
//strcpy(data,temp1); // works even outside this function, offcourse it must
data = temp1; //works inside this function, but not outside this function
printf("data %s\n", data);
}
int main()
{
int length1 = 0;
char data1[100] = "I am megharaj from india";
printf("data1 %s\n", data1);
reverse(data1);
printf("reversed\n");
printf("data1 %s\n", data1);
return 0;
}
数据=临时1;这在反向函数中起作用,但在主函数中不起作用。 是的,这是默认的,所以一旦它出现在函数之外,它就不会出现在堆栈上,但是为什么在主函数 data1 中打印字符串“I am megharaj from india”,我希望它打印垃圾值 因为我已经分配了一些东西,但它不再存在了,所以它必须打印垃圾值。为什么它保留其以前的地址。
最佳答案
temp
是 data
内容的副本,在 reverse
函数中本地放置在堆栈上。从最严格的意义上来说,C 中的所有内容都是按值传递的。当我们按值传递时,我们将变量的副本传递给函数。 它将数组地址的值复制到函数中。
data = temp1; this works in reverse function, but does not work in main function. yes, that is default so once it comes outside the function it will not be present on stack
这不是唯一的原因,temp1
是一个反向的本地数组,您无法在 reverse
函数之外访问它(因为它不是全局可见的) 反向
)。
所以有2个数组
+---+---+---+---+--+---+---+
| I am megharaj from india |
+---+---+---+---+--+---+---+ data1 in main
上面的内容在执行main
后被销毁。
+---+---+---+---+--+---+---+
| I am megharaj from india |
+---+---+---+---+--+---+---+ temp1 in reverse
上面的内容在执行reverse
后被销毁。
关于一旦退出函数,复制字符指针就没有效果,预期是垃圾值,但会恢复以前的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19806133/