Download presentation
Presentation is loading. Please wait.
Published byChloe Benson Modified over 8 years ago
1
CE-2810 Dr. Mark L. Hornick 1 “Classes” in C
2
CS-280 Dr. Mark L. Hornick 2 A struct is a complex datatype that can consist of Primitive datatypes Ints, floats, chars Arrays of any of the above Pointers to primitive datatypes Other structs or pointers to other structs
3
Is a struct something like a class? What’s missing? CS-280 Dr. Mark L. Hornick 3
4
CE-2810 Dr. Mark L. Hornick 4 Pointer review To define a pointer to a variable, we write: int* px; // unitialized pointer px = &x; // assume x is an int *px = 3; // set x=3 Point* pp1; // unitialized pp1 = &p1; // assume p1 is a Point pp1->x = 1; // set x member to 1
5
CE-2810 Dr. Mark L. Hornick 5 Function pointers Assume the functions with the following prototypes have been defined: int doSomething(int x, float y); int doSomethingElse(int x, float y); To define a compatible pointer pf to these functions, we write: int (*pf)(int, float);
6
CE-2810 Dr. Mark L. Hornick 6 Using a function pointer int doSomething(int x, float y); int doSomethingElse(int x, float y); int (*pf)(int, float); To assign the pointer to one of the functions: pf = doSomething; // NO PARENTHESES!! To call the function doSomething via the pointer: int status = pf(3, 4.0);
7
CE-2810 Dr. Mark L. Hornick 7 If a function is declared static, it can only be accessed from within the same source module (.c file) Essentially, the function is private to the module static int doSomething(int x, float y); Both prototype (declaration) and implementation (definition) have to be declared static.
8
Function pointers as struct members typedef struct Point { // declaration of Point struct float x; // x coordinate float y; // y coordinate int (*pf1)(int, float); // pointer to function void (*pf2)(void); // pointer to function } Point;// definition of Point datatype... Point pt1;// “object” of type Point; unitialized CS-280 Dr. Mark L. Hornick 8 Remember: local variables are not initialized in C global variables are initialized to 0
9
Initializing the struct Point pt1;// “object” of type Point; unitialized pt1.x = 3; Pt1.y = 4; Pt1.pf1 = ??? // initialize function pointers Pt1.pf2 = ??? Pt1.pf1(3,4.0); CS-280 Dr. Mark L. Hornick 9 Is there another way to initialize?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.