2,192 views
2 votes
2 votes
int main()
{
    static char a[5][20]={"mona","vijay","kumar","Nakuru","suresh"};
    int i;
    char *p;
    p=a[3];
    a[3]=a[4];
    a[4]=p;
    for(i=0;i<=4;i++)
        printf("%s",a[i]);
}



which line causes compile time error Nd why

2 Answers

Best answer
5 votes
5 votes

These both statements would cause error
1) a[3]=a[4]; 

2) a[4]=p;


For a 2-d array (assume it's a[3][4])

a[0] represent the address of first 1-d array (first row).

a[1] represent the address of the second 1-2 array (second row).

i mean to say for a 2-d array a[i] would be an address actually, in other words you can say for a 2-d array a[i] represent the pointer constant to ''i+1'' 1-d array. More over this pointer is a constant (cannot be made to point to something else) as all arrays are constant pointers in C. 

For an assignment to be valid, the left operand must refer to an object , i mean it must be an 'Lvalue'.

To ensure that these pointers ( in your example a[3] , a[4]) are not changed, in C array names may not be used as variables on the left of an assignment statement, i.e. they should not be used as an Lvalue except in initialization.

So These two assignments would result in an error because they are assigning values to constant pointers which is violating Lvalue rules.

you can read more here in case you want.

https://www.le.ac.uk/users/rjm1/cotter/page_59.htm

http://www-ee.eng.hawaii.edu/~tep/EE160/Book/chap7/subsection2.1.3.2.html

http://www.cs.yale.edu/homes/aspnes/pinewiki/C(2f)Pointers.html

PS: "static" has no relevance in the given code. 

selected by

No related questions found