使用c中的结构创建新对象

Asu*_*sur 4 c structure

我正在尝试使用c创建对象turbo c.我无法在其中定义属性.

/*
code for turbo c
included conio.h and stdio.h
*/



typedef struct {
  int topX;
  int topY;
  int width;
  int height;
  int backgroundColor;
}Window;

typedef struct {
  Window *awindow;
  char *title;
}TitleBar;


Window* newWindow(int, int, int, int, int);
TitleBar*  newTitleBar(char*);



void main() {
  TitleBar *tbar;       

  tbar = newTitleBar("a title");    
  /*
    the statement below echos,
    topX:844
    topY:170

    instead of
    topX:1
    topY:1

  */
  printf("topX:%d\ntopY:%d", tbar->awindow->topX, tbar->awindow->topY); 
  /*
    where as statement below echos right value 
    echos "a title"
 */
  printf("\ntitle:%s", tbar->title); 

  //displayTitleBar(tbar);      
}


Window* newWindow(int topX, int topY, int width, int height, int backgroundColor) {
  Window *win;
  win->topX = topX;
  win->topY = topY;
  win->width = width;
  win->height = height;
  win->backgroundColor = backgroundColor;
  return win;
}


TitleBar* newTitleBar(char *title) {
  TitleBar *atitleBar;      
  atitleBar->awindow = newWindow(1,1,80,1,WHITE);   
  atitleBar->title = title;
  return atitleBar;
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

定义结构的正确方法是什么?

pep*_*er0 14

你只需声明一个指针:

  Window *win;
Run Code Online (Sandbox Code Playgroud)

并尝试在下一行写入,而指针仍然没有指向任何有效的对象:

  win->topX = topX;
Run Code Online (Sandbox Code Playgroud)

您可能想要创建一个新对象:

  Window *win = (Window*)malloc(sizeof(Window));
Run Code Online (Sandbox Code Playgroud)

与TitleBar相同.