0

Say there is a common c array of type char *. I want to replace the value of a specific element, say index 0, by replacement. My code results in a segfault. What is the problem?

#include <string.h>

char * data[] = {
  "aaa",
  "bbb",
  "ccc"
};

int main(int argc, char *argv[])
{
  char * replacement = "xxx";
  strncpy(data[0], replacement, 3);
  return 0;
}
  • 2
    See duplicate, unless you just wanted to do `data[0] = replacement;`? Also, `strncpy` needs space for the null terminator; pass 4. – Ry- Jan 14 '17 at 01:30
  • String literals may not be writable, and `data` is an array of pointers pointed at string literals. – Dmitri Jan 14 '17 at 01:30
  • when you define and declare an char pointer `char *p = {"acts as const char, or resides in read-only-memory"};`, the `char *p` gets stored as `const char *`. – pkthapa Jan 14 '17 at 01:49

0 Answers0