char str[100];
char *q;
what is the difference between q
and str
....aren't they both char*
Mind that I am talking about str
, not str[100]
char str[100];
char *q;
what is the difference between q
and str
....aren't they both char*
Mind that I am talking about str
, not str[100]
char str[100];
str
is the the name of an array object. It is not in any real sense a pointer.
But like any expression of array type, it is, in most contexts, implicitly converted to the address of (or equivalently, a pointer to) the array's first element. This implicit conversion yields a pointer value; there is no pointer object, so there's nothing that can be modified. (The resulting pointer value is of type char*
, not const char*
or char *const
.)
The applicable exceptions here are when str
is the operand of a unary &
or sizeof
operator.
char *q;
q
is the name of a pointer object, and like nearly any non-const
object it can be modified.
See section 6 of the comp.lang.c FAQ.
q
is an uninitialized pointer, while str
points to somewhere 100 bytes are allocated.
Also, you can change where q
points to. But you cannot change the address of str
later.
By convention the name of an array is a constant which its value is the address of first element of it.
In most cases when str
is used in an expression or a statement it's implicitly converted to The address of the first element of the array. And one of the exceptions is with the sizeof
operator. In this case (sizeof(str)
), str
is the array itself and it is not converted to an address and that's why sizeof(str)
results 100
.
In term of accessing the data in the string, yes, str
can be thought of as a char*
, or more accurately, a char *const
because you cannot assign a different address to str
.
Strictly speaking, they are different types, which is why you can't assign a new value to str
. Think of it like the compiler: every variable is just a label for a particular address that it will allocate for you. str
, represent an address of the start of a buffer made up of 100 char
s, but q
is the address of an address, which in turn is the address of a char
.
You can change the value of a variable, but you can't change (at run time) where a variable is placed (i.e., its address).
In that example str is of type char[100], whereas q is a pointer to a char. It could point to any single array element of type char, but not to an array of type char.