字符数组VS字符指针用C [英] Char array vs Char Pointer in C
问题描述
我试图理解C指针,但我现在困惑与以下内容:
I am trying to understand pointers in C but I am currently confused with the following:
char *p = "hello"
- 这是在字符数组一个字符指针指向,开始为H
- this is a char pointer pointing at the character array, starting at h
char p[] = "hello"
- 这是一个存储你好阵列
- this is an array that stores hello.
有什么区别时,我通过这两个变量进入此功能?
What is the difference when I pass both these variables into this function?
void printSomething(char *p)
{
printf("p: %s",p);
}
我不明白它们是如何不同。
I do not understand how they are different.
推荐答案
的char *
和的char []
是不同类型的,但它不会立即显现在所有情况下。这是因为阵列的衰变为指针的,也就是说,如果提供的类型的char []
的前pression那里类型的一个的char *
预计,编译器阵列会自动转换成一个指向它的第一个元素。
char*
and char[]
are different types, but it's not immediately apparent in all cases. This is because arrays decay into pointers, meaning that if an expression of type char[]
is provided where one of type char*
is expected, the compiler automatically converts the array into a pointer to its first element.
您例如函数 printSomething
期望一个指针,所以如果你尝试到一个数组中传递给它这样的:
Your example function printSomething
expects a pointer, so if you try to pass an array to it like this:
char s[10] = "hello";
printSomething(s);
这是你写了这个编译器pretends:
The compiler pretends that you wrote this:
char s[10] = "hello";
printSomething(&s[0]);
这篇关于字符数组VS字符指针用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!