Search⌘ K

Discussion: Time to Pull Out Your Hair

Explore the behavior of string declarations in C, focusing on pointer versus array strings. Understand memory allocation, how the const qualifier affects string manipulation, and why array strings offer more flexibility. This lesson clarifies key concepts to help you avoid common pointer-related pitfalls in C programming.

Run the code

Now, it's time to execute the code and observe the output.

#include <stdio.h>

void modify(char *c)
{
  *(c+1) = 'o'; 
}
int main()
{
  char *string = "cat";
  printf("Before: %s\n", string);
  modify(string);
  printf("After: %s\n", string);
  return(0);
}
C code for the given puzzle

Understanding the output

The output might be a surprise:

Before: cat
Segmentation fault (core dumped)
Code output

Yes, it’s a pointer problem. It’s just not the pointer problem you may think it is. The issue lies in the construction of the string “cat”. ...