-1

I'm given a function that has a const char* as a parameter in C. How do I convert it to a regular char* in order to do string operations on it? When I have the following, I get the following: warning: initialization discards ‘const’ qualifier from pointer target type [enabled by default]

char* pathname_lookup(const char* pathname) {
    assert (pathname[0] == '/');
    char* path = ""; 
    strcpy(path, pathname);
    path = path + 1;
    return path;
}

How do I convert the const string into a string I can do string operations on?

hkitano
  • 119
  • 1
  • 3
  • 7

2 Answers2

4
char* path = ""; 
strcpy(path, pathname)

This doesn't make sense. Here, path points to a constant. So when you try to copy a string into it, you're trying to change a constant which, of course, you can't do because by definition, constants cannot have their value changed.

Perhaps you want:

char *path = strdup(pathname);
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
2

Your code is broken, it tries to copy the incoming string into the space occupied by the string literal "", which is illegal (literal strings are read-only).

You must allocate heap memory and copy the string in there.

This can be done with strdup(), which isn't standard but pretty common.

You can re-implement it like so:

char * my_strdup(const char *s)
{
  char *out = NULL;
  if(s != NULL)
  {
    if((out = malloc(strlen(s) + 1) != NULL)
      strcpy(out, s);
  }
  return out;
}

The above could be micro-optimized but that should suffice for most uses.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • One thing C teaches over the years is humility... Check my new question: http://stackoverflow.com/questions/32944390/what-is-the-rationale-for-not-including-strdup-in-the-c-standard – chqrlie Oct 05 '15 at 08:44
  • @chqrlie Absolutely. And ouch. – unwind Oct 05 '15 at 08:51