Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char * and char[]

Tags:

c++

Why is this right ?

#include<iostream>
using namespace std;
int main()
{
    char *s="raman";
    char *t="rawan";
    s=t;
    cout<<s;

return 0;
}

But this is wrong?

#include<iostream>
using namespace std;
int main()
{
    char s[]="raman";
    char t[]="rawan";
    s=t;
    cout<<s;

return 0;
}
like image 650
Gautam Kumar Avatar asked Nov 27 '22 22:11

Gautam Kumar


2 Answers

In the first example, s=t does a pointer assignment. In the second, s=t tries to assign a pointer value (resulting from the implicit conversion, or "decay", of the array expression t) to an array object. C++ doesn't permit array assignments.

C and C++ happen to be very similar in this area; section 6 of the comp.lang.c FAQ covers the relationship between arrays and pointers very well.

like image 167
Keith Thompson Avatar answered Nov 30 '22 23:11

Keith Thompson


The first example assigns an pointer to another which is valid.

The second example assigns an array to another array which in not allowed in C & C++ both.


This excellent C++ FAQ entry and this answer should be a good read for you.

like image 20
Alok Save Avatar answered Nov 30 '22 22:11

Alok Save