-5

The following code doesnt copy the contents of matches 2 to keys[0]. Why is that so?

char **keys;
char matches[2000];
char *matches2;
matches2 =strtok(matches," ");
strncpy(keys[0],matches2, sizeof keys[0]);
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • `sizeof keys[0]` is `sizeof char*`... – nneonneo Apr 10 '14 at 19:44
  • does not compile that way – user3521003 Apr 10 '14 at 19:48
  • @user3521003: Does not compile what way? nneonneo wasn't suggesting a fix to the code, he was pointing out a problem. Syntactically, it's `sizeof (char*)` rather than `sizeof char*`, but that's *not* the correct size to use. Furthermore, you haven't initialized `keys`, so `keys[0]` is meaningless. Finally, `strncpy()` is rarely the right function to use; see [my rant on the topic](http://the-flat-trantor-society.blogspot.com/2012/03/no-strncpy-is-not-safer-strcpy.html). – Keith Thompson Apr 10 '14 at 19:51

2 Answers2

1

You forgot to allocate space for keys to point to, as well as space for keys[#] to point to.
Also, are you really sure you want to use strncpy? It does not guarantee 0-termination, instead copying at most n byte of the ggiven string and 0-filling the rest of the buffer.

The size for a string is the number of elements including 0-terminator: strlen(s)+1

For creating a copy of a string, you might look into non-standard strdup, a possible implementation:

char* strdup(const char* s) {
    size_t n = strlen(s)+1;
    char* r = malloc(n);
    if(r)
        memcpy(r, s, n);
    return r;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • keys[0]=(char*)malloc(20*sizeof(char)); strncpy(keys[matches_number],matches2, 20*sizeof(char)); is this correct? not working ... – user3521003 Apr 10 '14 at 20:06
  • @user3521003: ??? What do you mean to say? Aside: Never cast the return value of `malloc` and the like, it only hides errors. – Deduplicator Apr 10 '14 at 20:07
0

Try this assuming that you already have allocated space for keys[0]

strncpy(keys[0], matches2, /*your desired size*/);

or

strcpy(keys[0], matches2);