0
char jpgname[8]; // Correct declaration
char *jpgname = "000.jpg"; // Incorrect declaration
.
.
sprintf(jpgname,"%03i.jpg", fileNum); // Segmentation fault seemed to occur on 
this line if the incorrect declaration method is used

Not a vital question for this pset but I do not understand why the second method of declaration does not work in this case.

I understand the need to allocate enough memory space when declaring, and that is what I have done by assigning to char* a string value whose length should be sufficient for the subsequent sprintf function.

0

char *jpgname = "000.jpg"; declares what is known as a string literal. String literals are stored in a special read-only part of memory, so if you try to alter the value, your program will segfault.

2
  • Thanks for the reply. So now I get that string literals and char arrays are stored in different types of memory shall I say. However if string literals are stored in a read-only part of memory, how does it work if I assign another string value to the variable? eg. jpgname = "001.jpg";
    – Nick Chan
    Oct 31 '18 at 5:44
  • Then you have a second string literal. And the string pointers will point to the second literal from that moment on. There's a good explanation in the lecture video's. Oct 31 '18 at 6:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .