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]);
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]);
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;
}
Try this assuming that you already have allocated space for keys[0]
strncpy(keys[0], matches2, /*your desired size*/);
or
strcpy(keys[0], matches2);