I am trying to create objects in c using turbo c
. I am having trouble defining attributes in them.
/*
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;
}
What am i doing wrong?
What is the proper way of defining structures?
Variables of the structure type can be created in C. These variables are allocated a separate copy of data members of the structure. There are two ways to create a structure variable in C.
Using the New Keyword to Create Objects Another way to create an object from a struct is to use a new keyword. While using a new keyword, Golang creates a new object of the type struct and returns its memory location back to the variable. In short, the new keyword returns the address of the object.
A struct object can be created with or without the new operator, same as primitive type variables. Above, an object of the Coordinate structure is created using the new keyword.
Create struct Variables When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables. Another way of creating a struct variable is: struct Person { // code } person1, person2, p[20];
You just declare a pointer:
Window *win;
And try to write there in the next lines, while the pointer still doesn't point to any valid object:
win->topX = topX;
You probably wanted to create a new object:
Window *win = (Window*)malloc(sizeof(Window));
The same with TitleBar.
Your pointers are never actually assigned to anything. In C, a pointer does not exist by itself, it needs an actual object in memory to point to.
This page has more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With