我知道这是一个非常基本的问题。我搞不懂为什么和怎么会有以下的不同。
char str[] = "Test";
char *str = "Test";发布于 2011-09-27 11:56:03
char str[] = "Test";是一个chars数组,使用来自“测试”的内容进行初始化,而
char *str = "Test";是一个指向文字(常量)字符串"Test“的指针。
它们之间的主要区别是第一个是数组,另一个是指针。数组拥有它的内容,这些内容恰好是"Test"的副本,而指针只是指向字符串的内容(在本例中是不可变的)。
发布于 2014-09-10 09:27:06
不同之处在于使用的堆栈内存。
例如,当为微控制器编程时,为堆栈分配的内存非常少,这会产生很大的差异。
char a[] = "string"; // the compiler puts {'s','t','r','i','n','g', 0} onto STACK
char *a = "string"; // the compiler puts just the pointer onto STACK
// and {'s','t','r','i','n','g',0} in static memory area.发布于 2011-09-27 12:03:22
指针可以重新指向其他内容:
char foo[] = "foo";
char bar[] = "bar";
char *str = foo; // str points to 'f'
str = bar; // Now str points to 'b'
++str; // Now str points to 'a'递增指针的最后一个示例显示,您可以轻松地遍历字符串的内容,一次迭代一个元素。
https://stackoverflow.com/questions/7564033
复制相似问题