简体   繁体   中英

c code: error in the syntax of structs and their fields

So i wrote the following code.

NameOfStruct *S;
if (statement) {
    S = (S)->property[10];
}

I defined the structure beforehand. So the error i am getting is this:

'*S' is a pointer; did you mean to use '->'? and then the line where i typed the code. I find this weird since they ask me if i meant -> while that is exactly what i use. If i instead use the following code

S = (*S)->property[10]

then i get that that there is a wrong assignment with an incompatible pointer type. What is happening here?

Your question is kind of hard to understand, but I think I understood enough to help you.

I think your problem might be in the way you defined the struct, and not on the code that uses it. Firstly, I don't know what NameOfStruct is, so i'll define one in this example:

typedef struct test {
    int someValue;
    char someString[10];
}EXAMPLE;

What this does is define a struct. You can either call for struct test or EXAMPLE when you want to do something with that struct.

Now, when it comes to use that struct, you can only use -> when you are dealing with pointers. Also, when using Structs, you should allocate memory using malloc() .

In your main, you should have something like this:

int main () {
    //Declare pointer to struct and allocate memory.
    EXAMPLE *test = (EXAMPLE*) malloc(sizeof(EXAMPLE));
    
    //Manipulate data on struct
    test->someValue = 10;
    test->someString = "Testing";
    free(test);
}

This way, you should be left with a struct where on someValue the content is 10 and on someString the content is Testing

Also, if in your main you don't feel like using EXAMPLE you can also just use struct test . Don't forget to free the memory you allocated when you don't need it anymore.

PS: Please, next time you ask a question be sure to give a good explanation on what the problem is, show us what your attempt was, and give us the input/output you were expecting paired with the input/output that you got. If you're left with any questions, feel free to reply to this answer and I'll try to help you

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