char *name;
cout<<name;

and

char*name;
name=new char[20];
cout<<name;

both of these work....then why do i need memory allocation....where does the first code fails

in your first example, the 'name' variable stores the address of an area of the memory that you do not know. this can be any value. When you try to print it, using 'cout<<', This should always crash, reporting a 'segmentation fault', as this operation will try to read the content of the memory at a random address.

Your second example is a bit better, because you allocate the memory (20 bytes) before using it.

The problem is that character strings are stored with a terminating '\0' character (a byte set to 0) that delimits the end of a character string.
As the content of your array is not defined yet, you may also have a problem, because the 'cout<<' operation will read the content of the array UNTIL it finds a '\0' character. This may happen inside your array, or not ! In the latter case, You will also try to read memory that you do not own.

So in general :

always be sure that you are working with memory that you own
always be sure of the content of this memory;

The correct code (for writing an empty string (!?)) may be :

char *name=new char[20];
name[0]='\0';
cout<<name<<endl;
delete name; //always release allocated memory

Ist Code

#include<iostream>
using namespace std;
int main()
{

char *name;
name="Sunny";
cout<<name;
return 0;
}

2nd Code

#include<iostream>
using namespace std;
int main()
{

char *name;
name=new char[20];
name="Sunny";
cout<<name;
return 0;
}

Both The Codes Works Fine.....Now What??Why Memory Allocation

Because in code 1 the string "sunny" is readonly. In code 2 the string "sunny" is writeable to.

Both The Codes Works Fine.....Now What??Why Memory Allocation

There are many many cases where you do not know the text that the character array contains. For example, suppose I ask you for your name. The program has to put the answer some place, if the pointer doesn't point to some value memory locations then your program will crash big time.

// allocate space to put your name, up to 79 characters
char *name = malloc(80);
// display the prompt
printf("Enter your name");
// get name from keyboard
fgets(name,80,stdin);

the above could also be done like this

// allocate space to put your name, up to 79 characters
char name[80];
// display the prompt
printf("Enter your name");
// get name from keyboard
fgets(name,80,stdin);

Because in code 1 the string "sunny" is readonly. In code 2 the string "sunny" is writeable to.

Thanx....i got it...its only read only

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.