diffrence between char s[]="hello"; or char *s ="hello"


/*
HIOS@Study material
Topic :: Different between
1: char s[]=" hios technology ";
2: char *s=" hios technology " ;
*/
#include <iostream>
using namespace std;
char *getString1()
{
char str[] = "you love me ?";
return str;
}
char *getSring2()
{
char *str="i love you !";
return str;
}
int main()
{
cout<<getSring2();
cout<<endl;
cout<<getString1()<<endl;
}
/* out put
i love you
Some garbage value
*/
#Explanation
char * allocates a pointer, while char [] allocates an array. Where does the string go in the former case, you ask? The compiler secretly allocates a static anonymous array to hold the string literal.
char *x = "Foo";
// is approximately equivalent to:
static const char __secret_anonymous_array[] = "Foo";
Note that you must not ever attempt to modify the contents of this anonymous array via this pointer; the effects are undefined (often meaning a crash):
x[1] = 'O'; // BAD. DON'T DO THIS.
Using the array syntax directly allocates it into new memory. Thus modification is safe:
char x[] = "Foo";
x[1] = 'O'; // No problem.
However the array only lives as long as its contaning scope, so if you do this in a function, don't return or leak a pointer to this array - make a copy instead with strdup() or similar. If the array is allocated in global scope, of course, no problem.
char s[]="string" // initialised in data segment
char *s="string " // initialised in "text" segment of the program
//source#stackoverflow.com
view raw diff.cpp hosted with ❤ by GitHub

Comments

Popular posts from this blog