5

Possible Duplicate:
C - Difference between “char var[]” and “char *var”?

I have written the following C code

#include<stdio.h>
int main()
{
    char name[31];
    char *temp;
    int i ;
    scanf("%s",name);
    temp  = name;
    name = temp;

}

I got the following error when compiling

incompatible types when assigning to type 'char[31]' from type 'char *'

Array name is a pointer to first element(here char pointer ..right?). right? The above code means that character array and char* are different types ..Is it true? Why is the type of name != char *? Why can I assign another char pointer to a char pointer (the name array)?

Løiten
  • 3,185
  • 4
  • 24
  • 36
Jinu Joseph Daniel
  • 5,864
  • 15
  • 60
  • 90

5 Answers5

10

Array name is a pointer to first element(here char pointer ..right?). right?

Wrong. Arrays decay to a pointer to the first element in most contexts, but they certainly aren't pointers. There's a good explanation in the C FAQ and an invaluable picture (a is an array and p is a pointer):

Arrays and pointers

incompatible types when assigning to type 'char[31]' from type 'char *'

In C arrays are non-modifiable lvalues, you can't change what they point to since they don't point anywhere in the first place.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
6

"Array name is a pointer to first element(here char pointer ..right?). right?"

char name[31];
char *temp;
/* ... */
name = temp;

In the name = temp assignment, the value of name is converted to a pointer to char. The value is converted, not the object. The object is still an array and arrays are not modifiable lvalues. As the constraints of the assignment operand require the left operand of the assignment operator to be a modifiable lvalue, you got an error.

ouah
  • 142,963
  • 15
  • 272
  • 331
1

First, arrays are memory buffers, not pointers, although they might be decayed to pointers when needed.

Now, nameis an array, so you cannot assign to it. when you assign an array to a pointer, the array is decayed to a pointer, and the assignment is valid.

MByD
  • 135,866
  • 28
  • 264
  • 277
1

No, the pointer points towards an object of the same type. This means a pointer can be used as a fully fledged array if it's allocated properly.
A NON pointer means you have the data here "in front of you", which doesn't let you properly get the data (also has time-of-life problems), so to be honest, pointers are better to be used everywhere in your case.

1

Because 'name' is an array. So This line:

name = temp;

will give you error.

Also your condition in the for loop is wrong. name[] will have junk values and you can't use

name[i]!='\0'

as a condition.

P.P
  • 117,907
  • 20
  • 175
  • 238