[英]What happens under the hood when you pass a string to a function in C
Does the compiler convert it to a string literal?编译器是否将其转换为字符串文字?
Is there any difference between these two?这两者之间有什么区别吗?
printf("Hello world\n");
and和
char* c = "Hello world\n";
printf(c); //I know you shouldn't do this
A string is just an array of char
(where content is terminated by the presence of a nul character).字符串只是一个
char
数组(其中内容因 nul 字符的存在而终止)。
char s[] = "Hi"; // These two declarations
char s[] = { 'H', 'i', '\0' }; // are equivalent
Arrays are not first class citizens in C. They cannot be passed to or returned from functions.数组不是 C 中的一等公民。它们不能传递给函数或从函数返回。
Pointers , on the other hand, are scalar types and can be passed to and returned from functions just as any other scalar type: by value.另一方面,指针是标量类型,可以像任何其他标量类型一样传递给函数和从函数返回:按值。 That is, the value of the pointer (the memory address it holds) is passed to or returned from a function.
也就是说,指针的值(它所持有的内存地址)被传递给函数或从函数返回。
So when you type:所以当你输入:
puts( "Hello world" );
what happens is that the address of the first character of the literal array is passed to the function.发生的事情是将文字数组的第一个字符的地址传递给函数。
As you suspect, this is no different than:正如您怀疑的那样,这与以下内容没有什么不同:
const char * s = "Hello world"; // s is a pointer to read-only memory
puts( s );
Again, s
is a pointer containing the address of the first character in the literal array.同样,
s
是一个指针,其中包含文字数组中第一个字符的地址。 Its value (the address) is passed to the function.它的值(地址)被传递给函数。
If s
were an array:如果
s
是一个数组:
char s[] = "Hello world"; // s is an array, content copied from read-only memory
puts( s );
then the address of the first element of the array would be passed to the function.然后数组第一个元素的地址将被传递给函数。
You find this same thing true of any kind of array in C:您会发现 C 语言中任何类型的数组都存在同样的情况:
int xs[] = { 2, 3, 5, 7, 11, 13 };
some_function( xs );
The array itself is not passed to the function, but the value of the pointer &(xs[0])
is passed , where the value is the address of the first element of the array.数组本身并没有传递给函数,而是传递了指针
&(xs[0])
的值,其中的值是数组第一个元素的地址。
In C we call this “array-to-pointer decay”.在 C 语言中,我们称之为“数组到指针的衰减”。
(An array is an address, element type, and count of elements. A pointer is just an address and element type.) (数组是地址、元素类型和元素数量。指针只是地址和元素类型。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.