char * s = {' h','' l',' l','是什么意思? O'' \ 0'};在C中它与char * s ="你好";?有什么不同?

时间:2015-11-13 08:20:12

标签: c

char *s={'h','e','l','l','o','\0'}; ---发出警告说:

warning: (near initialization for ‘s’)
warning: excess elements in scalar initializer

但是char *s="hello";通过在只读内存中为6个字符分配内存空间并指向该特定位置来显示hello。

但究竟是什么char *s={'h','e','l','l','o','\0'};以及它有何不同?

3 个答案:

答案 0 :(得分:1)

"hello"这样的字符串文字被视为指向char的指针或char数组,具体取决于您使用它的方式。

char *s = "hello";    // treats the string literal as pointer-to-char
char s[] = "hello";   // treats the string literal as array-of-char

{'h','e','l','l','o','\0'}这样的初始化程序被视为数组。它不能分配给指针。

char *s = {'h','e','l','l','o','\0'};   // this is NOT valid
char s[] = {'h','e','l','l','o','\0'};  // same as char s[] = "hello"

答案 1 :(得分:0)

不同之处在于"hello"是字符串文字,{'h', 'e', 'l', 'l', 'o', '\0'}是初始化列表。将char*赋值给字符串文字的意思是只使指针指向字符串,而将char*赋值给初始化列表的意思只是将其赋值给第一个值(即被'h'转换为char*)。

使用初始化列表的正确方法是使用char数组:

char s[] = {'h', 'e', 'l', 'l', 'o', '\0'};

但是这里仍然存在差异,因为这样你应该得到一个可变缓冲区。这里初始化列表用作值列表,用于初始化数组中的元素。它是:

的捷径
char s[6];

s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '\0';

答案 2 :(得分:0)

#include <stdio.h>

int main (void) {

    char *s1 = "hello";                  /* creates a string literal   */
    char s2[] = {'h','e','l','l','o',0}; /* creates a character array  */

    printf ("\n s1 : %s\n s2 : %s\n\n", s1, s2);

    return 0;
}

<强>输出

$ ./bin/s1s2

 s1 : hello
 s2 : hello

字符数组 's2'字符串文字 's1'之间的主要区别在于字符串文字是已创建,以后无法更改。字符数组可以用作任何其他数组或以null结尾的字符串。

相关问题