C Programming - Pointers - Discussion

Discussion Forum : Pointers - Point Out Errors (Q.No. 2)
2.
Point out the error in the program
#include<stdio.h>

int main()
{
    int a[] = {10, 20, 30, 40, 50};
    int j;
    for(j=0; j<5; j++)
    {
        printf("%d\n", a);
        a++;
    }
    return 0;
}
Error: Declaration syntax
Error: Expression syntax
Error: LValue required
Error: Rvalue required
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
65 comments Page 4 of 7.

Prashant singh said:   1 decade ago
Array name itself act as a pointer and it is a constant pointer. So it can not be modified even if you apply a Lvalue to it still it would give you the same error. So you can't modify constant pointer.

Simply a constant pointer can not be modified.

Sudha said:   1 decade ago
@Sugan.

An "lvalue" of a variable is the value of its address, i.e. where it is stored in memory.

The "rvalue" of a variable is the value stored in that variable (at that address).

Deepali said:   1 decade ago
A is memory address & we can not use %d for address. We have to use unsigned int.

Jagan said:   1 decade ago
Here LValue means a[].

We have to specify printf("%d",a[i]); instead of 'a'.

Sanjay Yadav said:   1 decade ago
#include<stdio.h>

int main()
{
int a[] = {10, 20, 30, 40, 50};
int j;
for(j=0; j<5; j++)
{
printf("%d\n", a);
a++;//error because a is an r-value and we cant increment it
}
return 0;
}

//Correct form.

int *p;
p=a;
printf("%d",*p);
p++;

POOJA said:   1 decade ago
Very simple logic.

a is an array.
We can't perform following operations on array:

a++;
a--;
a+=2;
....

If pointer to an array will be there then we can perform above operations.

Chandru said:   1 decade ago
@Sudha, can you please explain me with example program?

Anil said:   1 decade ago
Arrays internally follows const pointer mechanism.

ex: int const *arr =(int*)malloc(10*sizeof(int));

Can you perform increment operation here. No never not possible.

int *arr =(int*)malloc(10*sizeof(int));

Here increment operation works.

So its not matter of L-value. We can't change array base address that's the answer. Because array internally for const pointer mechanism.

Atul yadav said:   1 decade ago
Simply replace a++; with a[j]++;

Bele said:   1 decade ago
What is the reason to make array names as cons pointer, and give them the address of the first element, if we give them the address of the first element why we can't modify them and get the other elements? is there security issue or performance or something else. By not making arrays names const ptr?


Post your comments here:

Your comments will be displayed after verification.