开发者

In C, can I keep strings as char* and then use pointers to point to other strings?

If I create a string like

char string[6] = "hello";
char* ptr = (char*) malloc(sizeof(string));
strcpy(ptr, string);

and then I do this:

char* ptr2 = ptr;

will it work?

In general, if I have a char* pointer to a string, can I make other pointers point to that string and the initial pointer point to another string?

[EDIT]

Thanks for your feedback but I'm a little confused. I'll try to take things from the beginning.

  1. I have my main in which I do a scanf to read a string which is of not fixed size but has a MAX length. I read it like this char* input; scanf("%as", &input);. I think the 'a' flag allocates automatically the required memory to fit the string.

  2. Then I have to call a function foo(char* s) which takes the string as input.

  3. Inside that function, I have to store the string in memory. I have two options: eit开发者_StackOverflow中文版her use the parameter or make a new malloc and strcpy and use the new string. Which of the two is correct? I just need to store the memory location of the string and refer to it later.

  4. If I use the parameter and store the memory location of it somewhere, is this safe or because the pointer to a string is constant will it cause any problems? Will making another string with malloc solve anything or is it the same thing?

Until now I have tried several combinations but I couldn't achieve what I wanted. Any help is appreciated.


char[6] string = "hello";

won't work at all. You mean char string[] = "hello";

And yes, you can have pointers alias each other, i.e. point to the same buffer. Be careful that you don't free both of them though, or use any of the aliasing pointers after one of them has been free'd.

This is, in fact, very useful. Consider the typical implementation of strcpy, which must return its first argument:

char *strcpy(char *dest, char const *src)
{
    char *p = dest;  // aliasing pointers
    while (*src != '\0')
        *p++ = *src++;
    return dest;
}

And yes, after char *p2 = p1, you can point p1 at another buffer, but that's mainly useful in tricky pointer algorithms. Again, be careful with memory allocation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜