简体   繁体   中英

Incrementing char pointer inside C struct

For a char variable in C, you can normally increment through char pointers like so (this example just gets rid of spaces in a string):

void remove_spaces(char *str)
{
    const char *ptr = str;

    do
    {
        while (*ptr == ' ')
        {
            ++ptr;
        }
    } while (*str++ = *ptr++);
}

int main()
{
    char string[20];
    strcpy(string, "foo bar");
    remove_spaces(string);
}

In the case that you pass a struct like this one:

struct line
{
    char string[20];
    char something_else[20]
};

void remove_spaces(struct line *str)
{
    const char *ptr = str->string;

    do
    {
        while (*ptr == ' ')
        {
            ++ptr;
        }
    } while (str->string++ = *ptr++); // incorrect syntax
}

int main()
{
    struct line str;

    strcpy(str.string, "foo bar");
    remove_spaces(&str);
}

What is the correct syntax to increment this line in the while loop:

while (str->string++ = *ptr++);

(Note: I need to pass the whole struct to the function as there will be other operations with other members of the struct as well)

A string in a struct is a string. You don't need to invent any special treatment for the latter. You already know how to deal with a string. Keep your original remove_spaces function, and forget the second variant altogether.

remove_spaces(str.string);

That's all.

You need a second pointer:

void remove_spaces(struct line *str)
{
    const char *ptr = str->string;
    char *ptr2 = str->string;

    do
    {
        while (*ptr == ' ')
        {
            ++ptr;
        }
    } while (ptr2++ = *ptr++); // incorrect syntax
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM