Can anyone explain me what is a difference between these lines of code
char *p = "String"; char p2[] = "String"; char p3[7] = "String";
In what case should I use each of the above ?
你不应该使用第三个,因为它是错误的。“字符串”需要7个字节,而不是5。
第一个是指针(可以重新分配到不同的地址) ,另外两个被声明为数组,不能被重新分配到不同的内存位置(但它们的内容可能会改变,使用 const来避免这一点)。
const
这个链接应该能满足你的好奇心。
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
char *p = "String"; means pointer to a string type variable.
意味着您预先定义了数组的大小,使其由不超过5个元素组成。注意,对于字符串,null“0”也被认为是一个元素。因此,这个语句会给出一个错误,因为元素的数量是7,所以它应该是:
char p3[7]= "String";
C 中的字符串表示为字符数组。
char *p = "String";
你声明了一个指针,它指向一个字符串,这个字符串存储在你的程序中的某个地方(修改这个字符串是未定义行为) ,这是根据 C 语言2 ed 编写的。
char p2[] = "String";
You are declaring an array of char initialized with the string "String" leaving to the compiler the job to count the size of the array.
char p3[5] = "String";
您声明了一个大小为5的数组,并使用“ String”对其进行初始化。这是一个错误,因为“字符串”不适合5个元素。
char p3[7] = "String"; is the correct declaration ('\0' is the terminating character in c strings).
char p3[7] = "String";
http://c-faq.com/~scs/cclass/notes/sx8.html