0

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 ?

11
  • 3
    In C++, string literals are always a const char *. Commented Apr 24, 2017 at 10:33
  • @SamVarshavchik Isn't in C++ string a different data type ? Commented Apr 24, 2017 at 10:33
  • 1
    std::string is a class in the C++ library. C++, like C, has string literal constants. Except that they're always a const char *, and, as you know, you can't assign a pointer to a const object to a pointer to a non-const object. Neither in C, nor C++. Commented Apr 24, 2017 at 10:34
  • @SamVarshavchik, does that mean, adding the const modifier in the function parameter and in the a's declaration fix this ? Commented Apr 24, 2017 at 10:39
  • Maybe, depending on whether tabulate will try to mutate the parameter you just const-qualified. Commented Apr 24, 2017 at 10:41

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Which standard of C supports this new initializer syntax?
@YePhIcK-- what new initializer syntax?
S\@StephanLechner I'm in a big pointer-array mess. Can you explain why char *a={1,2,3}; generates warnings ? (It compiles but gives segfault). Doesn't it mean. create an array of 1,2,3 and a will point to it's first location ? Or in C {..} is not an array at all but an initializer list for an array ?
Got it. Thanks. One more point for arrays are a lot different than pointers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.