在下面的 pusedo 代码中,函数 display 将 char* 作为输入参数,并传递了一个字符串“apple”。在函数中,字符串的元素是通过索引访问的。 这里没有字符串“apple”的内存,那么它是如何在显示函数中访问的
#include <stdio.h>
void display(char * str)
{
int i = 0;
while ('\0' != str[i])
{
printf("%c", str[i]);
i++;
}
}
int main()
{
display("apple");
return 0;
}
函数运行正常,输出为 apple。 这种方法在很多程序中都可以看到,但我想知道内存将在哪里分配给字符串“apple”。以及这种用法的潜在问题是什么。
最佳答案
Here there is no memory for the string "apple" then how this is getting accessed in the display function
字符串“apple”
当然有内存:字符串文字放在内存中,文字本身用作指向该内存的指针。确切的位置是实现定义的,但将字符串文字放在程序的可执行代码占用的内存段中是很常见的。
What are the potential problems in this usage?
没有。只要您不尝试分配到字符串文字的内存中,您就是安全的。
关于c - 在 C 中将字符串直接传递给输入参数为 char 指针的函数有哪些潜在问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24457567/