简体   繁体   中英

Pointer and arrays difference in C++ and C

I know C++ is completely different language than C. Yet C++ acts as a super set of C.

I don't know why this code compiles and runs with just a few warnings in C and throws errors like scalar object 'a' requires one element in initializer

Here it is:

#include<stdio.h>
int tabulate(char **head){
    //Stuffs here
}

int main(){
    char **a={"Abc","Def"};
    tabulate(a);
    return 0;
}

Are there any other difference which C++ brings for C codes regarding pointers and arrays ?

const char ** does not declare a pointer to an array but a pointer to a pointer to a const char -value. It is just that a type const char*[] decays to a const char** when passed, for example, as function argument. So a is a scalar object, and {"abc","def"} is an array initializer; therefore the error message scalar object 'a' requires one element in initializer .

Hence, use array syntax and it will work for both c++ and c:

#include<stdio.h>
int tabulate(const char **head){
    //Stuffs here
    return 0;
}

int main(){
    const char *a[]={"Abc","Def"};
    tabulate(a);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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