Jump to content

newbie to c. problem with structures

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
csepraveenkumar

csepraveenkumar

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
the following code gives this error on compiling
error
struct1.c: In function ‘main’:
struct1.c:7: error: expected expression before ‘{’ token
struct1.c:8: error: expected expression before ‘{’ token

the code is

#include<stdio.h>
main(){
struct point{
int x;
int y;
} x,y;
x={1,2};
y={3,4};
printf(" %d %d %d %d\n",x.x,x.y,y.x,y.y);
}

how do i initialize the variables x and y if i don't want to initialize them where i have defined them?

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
That's because you cannot assign an initializer list to a struct that has already been instantiated. Initializer lists ONLY occur during initialization, never afterward. You can do what you're trying to do like so:
#include <stdio.h>

int main(void)
{
    struct point
    {
        int x;
        int y;
    } x = {1, 2}, y = {3, 4};

    printf("%d, %d, %d, %d\n", x.x, x.y, y.x, y.y);
}
Now to complain about your code. Use indentation! int ALWAYS comes before main(), and if you don't have any parameters for main, put in (void). Spacing, and thus readability, matters, use it.

EDIT: If you don't want to initialize them where you have defined them you'll have to do it all individually. I've seen some hacks that will perform struct initialization within a loop, but I don't recommend it personally.
Wow I changed my sig!

#3
Aereshaa

Aereshaa

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 790 posts
Actually in c99 you can in fact assign structs, and make struct literals. Like this:
int main(void){
 struct t {int x} a;
 a = (struct t){10};
}

Watches: Nanoha, Haruhi, AzuDai. Listens to: E-Type, Dj Melodie, Nightcore.
"When people are wrong they need to be corrected. And then when they can't accept it, an argument ensues." - MeTh0Dz