Hey, Is there any difference between the 2 syntax,
ie, str = "This is a test"; and strcpy(str,"This is a test");

I think, both of them, malloc some random 200 addresses, and give the starting location of the 200 chunk to the pointer variable 'ptr'.

#include<stdio.h>

char* str;

int main(void)
{
 str = (char*)malloc(200 * sizeof(char));

 //str = "This is a test";
 strcpy(str,"This is a test");

 printf("\nAddress = %u",str);
 printf("\nContents = %s",str);

 return 0;
}

Yes there is a difference between the two

str = "Test", the pointer just simply points to a string literal that resides in read-only memory and whose memory was allocated by the compiler when the program was compiled. The compiler reserves a whole block of memory in your program for all the string literals. You don't have to do anything specific for this. Because it's in read-only memory it's contents cannot be changed.

strcpy(str,"Test") -- with this one you will have to allocate memory for str before you can call strcpy(). Two ways to do it

  1. static allocation, such as char str[255];
  2. dynamic alllocation such as using malloc()

Ancient Dragon is correct, but I'd like to point out that there is a difference between

char *str = "Test";
/* and */
char str[] = "Test";

In both cases, "Test" is a string that resides in read-only memory. In the first case, str is a pointer object that is initialized to the address of the read-only string, as Ancient Dragon described.

But in the second case, str is an array object, and the initialization actually copies the string from read-only memory into the new (read-write) array. This memory has automatic storage duration, so it disappears when str goes out of scope -- you don't have to worry about free()ing it like you do with malloc().

As an aside, this kind of automatic copying is possible only with initialization, not ordinary assignment, so the following is not valid:

char str[100];
str = "Test";

This is because an array name is not an lvalue. The other version,

char *str;
str = "Test";

is more or less fine, but you must be very careful if you ever modify the string because str points to read-only memory. If you don't try to modify the string, declare it as char const *str; instead.

commented: good points :) +0
commented: Good points indeed! +13

Thanx Ancient Dragon and Trentacle for your good explanation.

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.