void main() {
// code
}
#include <stdio.h>
#include <stdio.h>
void main() {
int n;
scanf("%d", &n);
printf("Hello world!\n");
}
struct name {
type member;
type member;
...
};
e.g.
struct Student {
int regNo;
float marks;
char section;
};
struct Student
is the name of the structure- It occupies 4 + 8 + 4 = 16 bytes of memory
typedef struct Student {
int regNo;
float marks;
char section;
} Student;
// All can be assigned and used at the same time
struct struct_example {
int integer;
float decimal;
char name[20];
};
// Only any 1 of them can be assigned/used at a time
union union_example {
int integer;
float decimal;
char name[20];
};
int main() {
struct struct_example s;
union union_example u;
s.integer = 10;
s.decimal = 10.5;
strcpy(s.name, "Hello World!");
u.integer = 10;
u.decimal = 10.5;
strcpy(u.name, "Hello World!");
printf("struct_example: %d %f %s\n", s.integer, s.decimal, s.name);
printf("union_example: %d %f %s\n", u.integer, u.decimal, u.name);
return 0;
}
-
Auto (Used by default)
-
Slowest access
-
Stored in stack
int a = 32;
-
-
Register
-
Fastest access
-
Used for variables that are accessed more times during program
register int x = 324;
-
-
Static
-
Faster than auto
-
Uses data segment
-
Initialized only one during compilation
static int x=324;
-
-
Extern
-
Global variable, can be accessed from any function
-
Can be used to access global variable from another file
- file1.c
int x = 324; int main(){ extern int val; printf("Global var %d", val); }
- file2.c
# include <stdio.h> # include "file1.c" extern int x; int main(){ printf("Global var %d", x); }
-
-
Wild pointer: pointer that has not been initialized
- Uninitialized pointers are known as wild pointers because they point to some arbitrary memory location and may cause a program to crash or behave unexpectedly.
int *ptr; *ptr = 32523; printf("%d", *ptr);
-
Dangling pointer: pointer that points to a memory location that has been deleted (or freed)
int *ptr = (int *)malloc(sizeof(int)); *ptr = 32523; free(ptr); printf("%d", *ptr);
-
Null pointer: pointer that has been initialized to NULL
- NULL is a macro defined in <stdio.h> header file. It is an implementation-defined null pointer constant. It may be defined as 0 or ((void *)0). It is guaranteed that if NULL is defined as 0 then it will always be a null pointer constant.
int *ptr = NULL; printf("%d", *ptr);