简体   繁体   English

指向结构指针内字符串中的字符

[英]Pointing to char in string inside a struct pointer

Normally in C you can point to a specific char of a string to obtain a substring.通常在 C 中,您可以指向字符串的特定字符以获得子字符串。 Example:例子:

char string[10];
strcpy(string, "foo bar");
char *substring = &string[4];

// string = "foo bar"
// substring = "bar"

But what would be the syntax when you are dealing with struct pointers?但是当你处理结构指针时,语法是什么? I thought it would be something like this but it returns garbage data:我认为它会是这样的,但它返回垃圾数据:

struct line
{
    char string[10];
    char substring[10];
};

void some_function(struct line *txt)
{
    *(txt->substring) = &(txt->string[4]);
}

int main()
{
    struct line text;
    strcpy(text.string, "foo bar");

    some_function(&text);
    printf("\n-%s-\n", text.string);
    printf("\n-%s-", text.substring); // returns garbage data

    return 0;
}

It seems you mean看来你的意思

void some_function(struct line *txt)
{
    strcpy( txt->substring, txt->string + 4 );
}

The data member substring does not have a pointer type.数据成员子串没有指针类型。 It is an array.它是一个数组。 So you may not assign a pointer to an array.所以你不能分配一个指向数组的指针。 You can copy elements of one array to another array.您可以将一个数组的元素复制到另一个数组。

As for this expression statement至于这个表情语句

*(txt->substring) = &(txt->string[4]);

then the left operand has the type char while the right operand has the type char * .那么左操作数的类型为char而右操作数的类型为char * So this assignment in any case does not make sense.所以这个赋值在任何情况下都没有意义。

If the structure would be defined like如果将结构定义为

struct line
{
    char string[10];
    char *substring;
};

then within the function you could write然后在你可以写的函数中

void some_function(struct line *txt)
{
    txt->substring = txt->string + 4;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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