Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

newbie to c. problem with structures


  • Please log in to reply
2 replies to this topic

#1 csepraveenkumar

csepraveenkumar

    CC Resident

  • Advanced Member
  • PipPipPipPip
  • 54 posts

Posted 12 February 2010 - 07:12 AM

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?
  • 0

#2 ZekeDragon

ZekeDragon

    CC Leader

  • Retired Mod
  • PipPipPipPipPipPipPip
  • 1263 posts

Posted 12 February 2010 - 07:20 AM

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.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#3 Aereshaa

Aereshaa

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 638 posts

Posted 13 February 2010 - 02:48 PM

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};
}

  • 0
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




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download