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()

Edited 4 Years Ago by Ancient Dragon

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.

Comments
Good points indeed!
good points :)
This article has been dead for over six months. Start a new discussion instead.