Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between char* and char[] in C [duplicate]

Tags:

arrays

c

pointers

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)

like image 305
Jinu Joseph Daniel Avatar asked Apr 07 '12 11:04

Jinu Joseph Daniel


People also ask

Are char * and char [] the same?

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).

Is char [] the same as string?

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.

What is a char * array in C?

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)

What is the difference between char * p and char * p?

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.


2 Answers

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.

like image 93
cnicutar Avatar answered Oct 04 '22 03:10

cnicutar


"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.

like image 36
ouah Avatar answered Oct 04 '22 02:10

ouah