gbox
gbox

Reputation: 829

Increment Of Pointer Of An Array

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main()
{
    int x = 100, i;
    double D[x];

    for(i=0; i < 100; i++)
        scanf("%f", D++);

    return 0;
}

The code has two errors:

  1. "%f" rather then "%lf" - compilation error

  2. D++ - compilation error

But why is D++ an error? as D is a pointer to the first element of the array and ++ can be used on an array, like pointers?

Upvotes: 0

Views: 59

Answers (2)

sara hamdy
sara hamdy

Reputation: 412

you should know that D isn't pointer to first element of array but is a name of array and name of array has a special feature as it has the address of the first element in array but can't be incremented or decremented as it isn't real pointer but it is only the address of the first element in array SO keep in your mind ( douple D[x]; "name of array"= D=&D[0]) SO if you want to increment to scan array elements by user there is two method firstly by using array

 for(i=0; i < 100; i++)
        scanf("%lu", D[i]);

secondly by using pointer

douple *ptr=&D[0];
for(i=0; i < 100; i++)
        scanf("%lu", *(ptr+i);

As you want to fill array elements by values

 *(D+i)=*(ptr+i)=D[i] 

at the same i

Upvotes: 0

dbush
dbush

Reputation: 223699

D is not a pointer to the first element of an array. D is an array, and an array "decays" into a pointer to its first element in most contexts.

The ++ operator cannot be used on an array because it modifies its operand, and an array is not modifiable (although its element are).

Upvotes: 4

Related Questions