0

I understand the concept of pointers and arrays in C. My problem is the syntax of them. What is this:

char* var;
char var*;

3 Answers 3

16

Your premise is wrong. The first is the pointer type and the second is well... nothing, it is not valid C++ (neither is C for that matter). Static arrays are more like this:

char var[15];

Dynamic arrays are on the other hand usually done with vectors.

The confusion between arrays and pointers is a legacy from the C programming language, where *(a+n) and a[n] mean the same thing, so we can use the a[n] even if a is a pointer, not an array. This is not very idiomatic in C++ though.

Sign up to request clarification or add additional context in comments.

Comments

7

char* var; declares var to be a "pointer to char". char var*; is not a valid declaration.

An array would be declared something like: char var[10];.

6 Comments

Or something like: std::array<char, 10> var;
@chris that's not an array, that's an std::array. But yeah, I'd recommend that.
@classdaknok_t, it's the ideal static array to be using if you have the resources available to do so.
@classdaknok_t of course it's an array. Just not a C-style array, but this question is about C++.
@SethCarnegie, of course, but the whole purpose of it is to replace the use of an array with a better alternative. We say std::string objects are strings, but strings in the base sense are still C-style character arrays. Hopefully std::array will take over in the same way one day.
|
3

This is a pointer:

char* var;

This is syntactically incorrect, and will not compile:

char var*;

Arrays and pointers in C++ are not the same thing, but the syntax might make it seem like they are. You can declare an array in C++ like this:

char ary[] = {'a','b','c'};

...and this is valid -- there will be an array created with 3 elements.

You can also create a function which takes a pointer:

void foo(char* bar)
{
// ...
}

...and pass it ary:

foo(ary);

...and it will compile and run fine. This might lead you to believe that pointers and arrays are the same thing; but they aren't. bar in foo above isn't an array -- it's a pointer that points to the first element of the array.

1 Comment

It might be worth mentioning that in the call foo(ary);, ary decays into the needed pointer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.