2012-03-05 15 views
2

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

私が間違って何をしているのですか?

構造を定義する適切な方法は何ですか?

+0

タイプミスではない場合、コードの重要な部分は、コメントが行番号4で閉じられていないため、コメントアウトされています。 – check123

答えて

11

あなただけのポインタを宣言します新しいオブジェクトを作成する:

Window *win = (Window*)malloc(sizeof(Window)); 

TitleBarと同じです。

2

あなたのポインタは決して何にも割り当てられません。 Cでは、ポインタはそれ自身では存在しません。ポインターにはメモリ内の実際のオブジェクトが必要です。

This pageがさらにあります。

Window *win; 

とポインタはまだ有効な任意のオブジェクトを指していない一方で、次の行であっ書いてみる:

win->topX = topX; 

あなたはおそらく望んでいた

関連する問題