Я не могу найти решение со следующим кодом C

У меня есть 3 файла:

1) story1.c

Где

struct Example1 
{
int first_element;           
int second_element;
...
};

int function1(Example1 *m, ...) 
{
...
m->first_element = m->second_element;
m->second_element = /* changing int data */;

return /* other integer */;
}

2) story1.h

Где

typedef struct Example1 Example1;

3) story2.c

Где

typedef struct Example2 {
Example1 *ptr;
int res2;
...
} Example2;

[...]

static void mother_function(Example2 *s)
{
int res;

res = function1(s->ptr, ...);
}

static void last_function(Example2 *s)
{
if ( ( &(s->ptr)->first_element == 10 ) &&
             ( (((*s).ptr).second_element) == 44 ) &&
             /* other conditions */ )
            s->res2 = /* new value */;
}

Mother_function вызывает функцию 1, которая устанавливает m-> first_element и m-> second_element, например 10 и 44

Теперь я хотел бы, чтобы last_function имел доступ к этим вновь рожденным [в функции1 другого файла] значениям, начиная с указателя s, чтобы оценить if [концептуально говоря, я хотел бы сделать что-то вроде:

if( (s->ptr->first_element==10) && (s->ptr->second_element==44) ) then...

Я пытался писать тремя способами:
1) s->ptr->first_element
2) ( &(s->ptr)->first_element == 10 )
3) ( (((*s).ptr).second_element) == 44 )

И компилятор выдал мне следующие ошибки:

1) error: dereferencing pointer to incomplete type
2) error: dereferencing pointer to incomplete type
3) error: request for member ‘second_element’ in something not a structure or union

В чем причина этих сообщений и как я могу практически исправить эту проблему?

Заранее спасибо тем, кто постарается помочь

0
Antonino 30 Янв 2015 в 21:01

2 ответа

Лучший ответ

Вам нужно переместить строки struct Example1 { ... }; из story1.c в story1.h (и убедиться, что story2.c включает story1.h), чтобы у story2.c был доступ к определение struct Example1. Тогда запись s->ptr->first_element должна работать.

3
jwodder 30 Янв 2015 в 18:05

Просто добавьте пояснение к решению Jwodder: s->ptr->first_element пытается получить доступ к члену struct Example1, однако struct Example1 определен в story1.c, поэтому он невидим для story2.c.

См. http://en.cppreference.com/w/c/language/scope

0
qweruiop 30 Янв 2015 в 18:24