Can't access field in struct

J

JS

I can't seem to access the field in this struct:

#include <stdio.h>

struct data{
int x;
int y;
};

static struct data test;
struct data *pp = &test;

pp->x = 23;





in the last line I get "parse error before "->" token.

How do I set x to 23?
 
V

Victor Bazarov

JS said:
I can't seem to access the field in this struct:

#include <stdio.h>

struct data{
int x;
int y;
};

static struct data test;
struct data *pp = &test;

pp->x = 23;





in the last line I get "parse error before "->" token.

How do I set x to 23?

The code you posted is not a valid C++ program. Please post the
real code you're having the problem compiling.

V
 
A

Artie Gold

JS said:
I can't seem to access the field in this struct:

#include <stdio.h>

struct data{
int x;
int y;
};

static struct data test;
struct data *pp = &test;

pp->x = 23;





in the last line I get "parse error before "->" token.

How do I set x to 23?
No way to tell from what you've posted. Please post a small
*compilable*[1] example.

HTH,
--ag

[1] Or one you think *should* be compilable. ;-)
 
J

JS

This is just it. But after trying a few things I found out its only possible
to access a field from a method.:

#include <stdio.h>

struct data {

int x;

int y;

};

struct data test;

main(){

test.x = 45;


printf("%d\n", test.x);

printf("%d\n", test.y);


getchar();



}



Now it works
 
V

Victor Bazarov

JS said:
This is just it. But after trying a few things I found out its only possible
to access a field from a method.:

#include <stdio.h>

struct data {

int x;

int y;

};

struct data test;

"struct" is superfluous here. This is C++, not C. Now, for the fun
of it, add

data *ptest = &test;

Change to

int main() {

otherwise it's not C++.
test.x = 45;

Replace this with

ptest->x = 45;

and you should have exactly same effect.
printf("%d\n", test.x);

printf("%d\n", test.y);


getchar();



}



Now it works

What it was that didn't work before we'll never know. See the FAQ,
section 5.

V
 
H

Howard

What it was that didn't work before we'll never know. See the FAQ,
section 5.

V

Judging from his comment: "I found out its only possible to access a field
from a method", perhaps he didn't have that code inside main?

-Howard
 
V

Victor Bazarov

Howard said:
Judging from his comment: "I found out its only possible to access a field
from a method", perhaps he didn't have that code inside main?

Perhaps. Do we actually care?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top