Reputation: 423
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)
Upvotes: 0
Views: 273
Reputation: 119877
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.
Upvotes: 2
Reputation: 126203
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
}
Upvotes: 1