简体   繁体   English

初始化一个指向字符指针的指针并初始化一个指针数组,每个指针指向一个字符指针

[英]initialize a pointer to a character pointer and initialize an array of pointer each pointing to a character pointer

I have a question regarding my code here:我在这里对我的代码有疑问:

    char a = 'A';
    char b = 'B';
    char c = 'C';
    char *ad = &a;
    char *ab = &b;
    char *ac = &c;
    char* cp[] = {ad, ab, ac}; 
    
    char **d = &(cp[2]);  // okay
    // char **d[0] = &(cp[2]);  //variant 1: error: invalid initializer
   // char **d[] = &(cp[2]);    //variant 2: error: invalid initializer

I am not sure why variant1 and variant2 would leads to error.我不确定为什么 variant1 和 variant2 会导致错误。 For the original initialization (ie the line with comment okay), there was no error.对于最初的初始化(即注释ok的那一行),没有错误。 My understanding is I have initialize a pointer (ie d) which is pointing to a pointer that pointing to a character.我的理解是我已经初始化了一个指针(即d),它指向一个指向一个字符的指针。 So this seems fine.所以这似乎很好。

For variant1, I thought (based on my understanding) I am initializing an array of pointers where each of them will point to a pointer that points to a character.对于variant1,我认为(根据我的理解)我正在初始化一个指针数组,其中每个指针都指向一个指向字符的指针。 So in this case, I only initialize the very first element in that array.所以在这种情况下,我只初始化该数组中的第一个元素。

Similarly for variant2, I initialize an empty array of pointers that each would points to a character.同样对于variant2,我初始化了一个空的指针数组,每个指针都指向一个字符。

Could someone tells me why there is error of coming from the compiler here?有人可以告诉我为什么这里的编译器有错误吗?

And is my understanding of variant 1 correct?我对变体 1 的理解是否正确? ie d is an array of pointers where each entry in the array would points to a pointer that points to a character??即 d 是一个指针数组,其中数组中的每个条目都将指向一个指向字符的指针? I thought this is correct.我认为这是正确的。 So why is it that I cannot initialize variant 1?那么为什么我无法初始化变体 1?

For variant2, I also thought that I have an array of pointers each pointing to a pointer that points to a character.对于variant2,我还认为我有一个指针数组,每个指针指向一个指向字符的指针。

This compiles cleanly...这编译得很干净......

char a = 'A';
char b = 'B';
char c = 'C';
char *ad = &a;
char *ab = &b;
char *ac = &c;
char *cp[] = {ad, ab, ac}; // be consistent

char **d    =   &cp[2];
char **e[1] = { &cp[2] }; // cannot dimension an array to have 0 elements
char **f[]  = { &cp[2] }; // compilers count more accurately than people

Note the absence of unnecessary "()".请注意没有不必要的“()”。

Array initialisers are listed within enclosing braces.数组初始化器列在大括号内。 "{}" “{}”

Exception to last statement: char foo[] = "bar";最后一条语句的例外: char foo[] = "bar"; ... "string" array elements do not require braces unless one gets silly: ...“字符串”数组元素不需要大括号,除非你很傻:

char foo[] = { 'b', 'a', 'r', '\0', };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM