purpleblau
purpleblau

Reputation: 589

array[0] = 0 how is this possible?

an array can't be defined as c[0], it at least has to be like c[1] Why is the following code correct? What is he doing there? Thank you for the explanation.

edit: sorry guys, I'm writing C++ code in VS2012

int foo(double c[], int n) 
{

    if (n==1) {
        c[0] = 0;      //why is this possible?
    } else {
.
.
.

}

Upvotes: 0

Views: 282

Answers (4)

Zoltán Schmidt
Zoltán Schmidt

Reputation: 1345

"an array can't be defined as c[0]"

It can be!

The array member with 0 number is the first member of the array.

The array member with 1 number is the second member of the array.

Overall:

The array member with X number is the X+1th member of the array.

It's not sorcery: the reason is that the computer doesn't count as we count, the decimal numeral system starts with number zero.

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363858

double c[], in argument position, is syntactic sugar for double *c; it's actually a pointer. Similarly, c[0] is sugar for *c.

c[0] = 0; is not an array declaration. It's an assignment to the first element of the array pointed to by c.

Upvotes: 6

siddstuff
siddstuff

Reputation: 1255

In addition, the array name c can be thought as a synonym for the address of the first element in the array. suppose we have array double c[] as, enter image description here

we already know that array index always start from 0

using c[0] notation, we can access the first element that is 21

but actually compiler convert c[0] to *(c+0) to access the first element.

similarly, we can directly use these pointer notation in our program.

For example, to access the third element which could be accessed using index c[2], we can use pointer *(c+2).

Thus , 
             in array ,  c[0] means *(c+0) 
                         c[1] means *(c+1) 
                         c[2] means *(c+2) and so on.

Upvotes: 2

sepp2k
sepp2k

Reputation: 370465

In a variable declaration c[0] means "c is an array of size 0". Since arrays of size 0 don't exist (and wouldn't make sense) in C or C++, that is, as you point out, illegal.

As an expression c[0] means "get the element at index 0 of c". Since C arrays are 0-indexed valid indices for an array of size n are 0 through n-1. Since the size of an array always has to be greater than 0, 0 is always a valid index for any array. So it's always legal to write c[0] if c is an array or a pointer to valid memory.

And since c[i] is an expression that produces an lvalue, it is also always legal to write c[0] = someValue (unless c is const).

Upvotes: 2

Related Questions