[英]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):对于 C 中的 char 变量,您通常可以像这样通过 char 指针递增(这个例子只是去掉了字符串中的空格):
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 循环中增加这一行的正确语法是什么:
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
函数,完全忘记第二个变体。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.