-3
char temp1[4] = "abc";
char *temp2 = "123";
strcpy(temp1,temp2);

if I want to copy a string literal to an array, it works well, but if I do it in the opposite way, I get an error:

char temp1[4] = "abc";
char *temp2 = "123";
strcpy(temp2,temp1);

The feedback from compiler is "Segmentation fault".

So what's the differences? Is there anyway to copy a string to a string literal?

Thx.

Eric Wang
  • 1
  • 2

2 Answers2

2

You need to understand the subtle difference between these 2 lines

char temp1[4] = "abc";
char *temp2 = "123";

The first one creates a 4 character variable and copies "abc\0" to it.
You can overwrite that if you want to. You can do e.g. temp1[0] = 'x' if you want.

The second one creates a pointer that points to the constant literal "123\0".
You cannot overwrite that, its typically in memory that is declared read only to the OS.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
pm100
  • 48,078
  • 23
  • 82
  • 145
1

What you have is more complicated than a string literal and what you attempt to do cannot be described as "copying to string literal". Which is good, because copying to a string literal is literally impossible. (Excuse the pun.)

First, what you are successfully doing in the first code quote is copying from a string literal into an array of chars of size 4 (you knew that). You are however doing this with the added detail of copying via a pointer to that string literal (temp2). Also note that what the pointer is pointing to is not a variable which can be edited in any way. It is "just a string which the linker knows about".

In the second code quote you attempt to copy a string (strictly speaking a zero-terminated sequence of chars which is stored in an array, temp1, but not a string literal) to a place where a pointer to char (temp2) points to, but which happens not to be a variable which is legal to write to.

The types of the involved variables allow such an operation basically, but in this case it is forbidden/impossible; which causes the segmentation fault.

Now what IS possible and might be what you actually attempt, is to repoint temp2 to the address at the beginning of temp1. I believe that is what gives you the desired effect:

char temp1[4] = "abc";
char *temp2 = "123";

/* Some code, in which temp2 is used with a meaningful
   initialisation value, which is represented by "123".
   Then, I assume you want to change the pointer, so that it points
   to a dynamically determined string, which is stored in a changeable
   variable.
   To do that: */
temp2=temp1;
/* But make sure to keep the variable, the name you chose makes me worry. */

Note that an array identifier can be used as a pointer to the type of the array entries.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54