As the heading says, What is the difference between
char a[] = ?string?; and
char *p = ?string?;
This question was asked to me in inter
The first one is array the other is pointer.
The array declaration
char a[6];
requests that space for six characters be set aside, to be known by the namea
. That is, there is a location nameda
at which six characters can sit. The pointer declarationchar *p;
on the other hand, requests a place which holds a pointer. The pointer is to be known by the namep
, and can point to any char (or contiguous array of chars) anywhere.The statements
char a[] = "string"; char *p = "string";
would result in data structures which could be represented like this:
+---+---+---+---+---+---+----+ a: | s | t | r | i | n | g | \0 | +---+---+---+---+---+---+----+ +-----+ +---+---+---+---+---+---+---+ p: | *======> | s | t | r | i | n | g |\0 | +-----+ +---+---+---+---+---+---+---+
It is important to realize that a reference like
x[3]
generates different code depending on whetherx
is an array or a pointer. Given the declarations above, when the compiler sees the expressiona[3]
, it emits code to start at the locationa
, move three elements past it, and fetch the character there. When it sees the expressionp[3]
, it emits code to start at the locationp
, fetch the pointer value there, add three element sizes to the pointer, and finally fetch the character pointed to. In the example above, botha[3]
andp[3]
happen to be the characterl
, but the compiler gets there differently.
Source: comp.lang.c FAQ list · Question 6.2
They do differ as to where the memory is stored. Ideally the second one should use const char *.
The first one
char buf[] = "hello";
creates an automatic buffer big enough to hold the characters and copies them in (including the null terminator).
The second one
const char * buf = "hello";
should use const and simply creates a pointer that points at memory usually stored in static space where it is illegal to modify it.
The converse (of the fact you can modify the first safely and not the second) is that it is safe to return the second pointer from a function, but not the first. This is because the second one will remain a valid memory pointer outside the scope of the function, the first will not.
const char * sayHello()
{
const char * buf = "hello";
return buf; // valid
}
const char * sayHelloBroken()
{
char buf[] = "hello";
return buf; // invalid
}