If I have an array of char and a char pointer, how can I make the compatible ?
Best wishes, DesmondCode:
void something(char *mstring)
{
char list[i] = ... // "Hello World"
mstring = list; ????? // Now I want mstring to return "Hello world"
}
Printable View
If I have an array of char and a char pointer, how can I make the compatible ?
Best wishes, DesmondCode:
void something(char *mstring)
{
char list[i] = ... // "Hello World"
mstring = list; ????? // Now I want mstring to return "Hello world"
}
It sounds like you want to copy from one string to another:
or perhaps a little safer:Code:void something(char *mstring)
{
char list[] = "Hello World";
strcpy(mstring, list);
}
Code:void something(char *mstring, size_t len)
{
char list[] = "Hello World";
strncpy(mstring, list, len);
}
How are you calling your function? It is unclear form your example what you want the function to do.
If you want to modify a char pointer in the calling routine, then you need to pass a char **. However, in that case you must either make list a const char pointer to a literal string, or static.
If you want to copy the string created in list to a buffer passed to you function, then you can use the strcpy() function found in <string.h>. However, you must first make sure the buffer is big enough.
Remember that strncpy() doesn't add a terminating NULL if there are at least len characters in the string . . . in other words, this is closer to being an equivalent of the first something():Quote:
or perhaps a little safer:
Code:void something(char *mstring, size_t len)
{
char list[] = "Hello World";
strncpy(mstring, list, len);
}
Also note that list could be of type const char * and it would still work. It would probably use less memory, too. ;)Code:void something(char *mstring, size_t len)
{
char list[] = "Hello World";
strncpy(mstring, list, len);
mstring[len] = 0;
}
isn't it out of bounds access?Quote:
mstring[len] = 0;
Generally, I think of string lengths in terms of strlen(). You know . . . buffer[strlen(buffer)] . . . malloc(strlen(buffer) + 1) . . . .
On the other hand there is fgets(), of course. :) But I have a convincing argument for my point of view!
strncpy() takes the maximum number of characters to copy -- in other words, a strlen()-like value. Thus, strncpy() could fill in mstring[0] ... mstring[len-1]. In order to avoid overwriting any of those characters, mstring[len] is the next logical index to use.Code:strncpy(mstring, list, len);
mstring[len] = 0;
It's just an idiom -- you know:
It's reasonably common . . . it's even in the example in the link I posted earlier in this post.Code:strncpy(a, b, n);
a[n] = 0;
But it doesn't matter, it's just an example. That's why it's called something(). ;)