简体   繁体   中英

Can a string be assigned to a char pointer, without it becoming a literal?

The question sounds a tad dumb, allow me to demonstrate what I mean.

I know that if I were to do something along the lines of:

(const) char *ptr = "I'm text!";

It'd be a literal I can't modify by any means later on. However, I figured, as there is a way to set up a pointer to work just like an array (on the heap), wouldn't it work to set up a string that way too? If yes, what'd be the easy way?

I tried the following, but it seems rather redundant, compared to just making an array and then assigning a pointer to it.

char *ptr = malloc(sizeof(char)*256);

ptr[0]='S';
ptr[1]='u';
ptr[2]='p';
ptr[3]='e';
ptr[4]='r';
ptr[5]='\0';

printf("%s\n", ptr);  

free(ptr);

You can do

char str[] = "eureka, this works";

Now you can modify the char s in it, using str , because it is essentially a char array. This means that certain operation like incrementing str++ will not work.


However, if you strictly want to work with a pointer, then you can add another line to the above code.

char str[] = "eureka, this works";
char* ptr = str;

Now you can use ptr , operations like incrementing and all will work, since it is a pointer.

After allocating space to char * ( as you talk about it in example ), instead of doing character by character , you can use strcpy -

char *ptr = malloc((sizeof *ptr)*256);
if(ptr!=NULL) {                     // check return 
     strcpy(ptr,"super");
     //do something 
} 
free(ptr); 

There is difference between character array initialization and char pointer initialization.

Whenever you initialize a char pointer to point at a string literal, the literal will be stored in the code section. You can not modify code section memory. If you are trying to modify unauthorised memory then you will get a segmentation fault.

But if you initialize a char array, then it will be stored in the data or stack section, depending on at where you declared the array. So you can then modify the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM