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 type of name != char * why i cannot assign another char pointer to a char pointer(array name)
The main difference between them is that the first is an array and the other one is a pointer. The array owns its contents, which happen to be a copy of "Test" , while the pointer simply refers to the contents of the string (which in this case is immutable).
char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars.
In C, an array of type char is used to represent a character string, the end of which is marked by a byte set to 0 (also known as a NUL character)
char* p and char *p are exactly equivalent. In many ways, you ought to write char *p since, really, p is a pointer to char . But as the years have ticked by, most folk regard char* as the type for p , so char* p is possibly more common.
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):
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.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With