762 views
1 1 vote
What means second statement means?

char x[]="WHATIZIT";

char *y="WHATIZIT";

1 Answer

Best answer
4 4 votes
char *y="WHATIZIT";

Here y is a charecter pointer meaning it contains the address of a character. But "WHATIZIT" has 9 characters (including the implicit NULL character at end) so how it works? The C/C++ compiler does a trick here. Whenever it encounters a string literal like "WHATIZIT", it stores it at a location (usually read only as literals are not meant to be modified like integer constants 2,3..) and returns the starting address of it. The starting address of a sequence of characters and that of the first character of the sequence is one and the same. And so we can assign it to a character pointer and this technique enables us to use strings in C even without a native string data type.  But the thing here is we are not explicitly allocating a memory for the characters and the compiler is thus treating it as a constant- side effect is we cannot modify the string. i.e., the following is not allowed:

y[0] = 'a';//We are not allowed to change the contents of the memory location of constants.  

Constant data might be in RO segment of memory and accessing them for Write can cause a segmentation fault from OS.

But we can do

y = "Hello"; //y is made to point to another string literal
char x[]="WHATIZIT";

Here, x is an array of characters and the size of the array is 9 (including NULL at end). In C/C++ an array is same as a pointer but is constant. i.e., it cannot be made to point to any other location like we can do for a pointer. But the values of the array can be changed as long as we do not overflow the bound. i.e., the following are valid:

x[0] = 't';
x[1] = 'l';

But the following are not

x[10] = 'p'; //overflow which can cause runtime error
x = "hello"; //x is a constant pointer 

In short *x here works like a pointer to a constant and x[] works like a constant pointer.

• selected by
Position:
Show:

Related questions

1 1 vote
1 1 answer
169
169 views
khanshahima4 asked Sep 24
169 views
1. If precedence tells me which operator has priority, and associativity tells me how to handle operators at the same level, then why do I need a separate concept called ...
13 13 votes
1 1 answer
1.3k
1.3k views
GO Classes asked Jul 2
1,265 views
Assume:$\texttt{short = 2 bytes}$, $\texttt{int = 4 bytes}$, $\texttt{char = 1 byte}$$\texttt{int}$ needs $4$-byte alignment and the final structure size is rounded to a ...
16 16 votes
2 2 answers
683
683 views
GO Classes asked Jul 2
683 views
Assume:struct Student { double gpa; }; struct Student alice; struct Student *sptr = &alice;Which of the following correctly assigns $\texttt{4.0}$ to $\texttt{alice.gpa}$...
9 9 votes
1 1 answer
506
506 views
GO Classes asked Jul 2
506 views
Consider the following code idea from the source:typedef struct { double x, y; } Point; void reset(Point p) { p.x = p.y = 0; } int main() { Point a = {12.0, 42.0}; Point ...