General Notes
General Notes
Memory
1. Tools for C Programming
To start coding in C, you need:
void example() {
int a = 10; // Stored in Stack
int *ptr = malloc(4); // Allocated in Heap
}
int main() {
example();
return 0;
}
struct Student {
char name[50];
int age;
float gpa;
};
int main() {
struct Student s1 = {"Alice", 20, 3.5};
printf("Name: %s, Age: %d, GPA: %.2f\n", s1.name, s1.age, s1.gpa);
return 0;
}
● struct Student groups name, age, and gpa into a single object.
Function Description
int main() {
FILE *file = fopen("data.txt", "r");
char line[100];
if (file) {
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
} else {
printf("Error opening file!\n");
}
return 0;
}
2. Pointers in C
A pointer is a variable that stores the memory address of another variable.
int main() {
int num = 42;
int *ptr = # // Stores address of num
Function Description
int main() {
int *arr = malloc(5 * sizeof(int)); // Allocates memory for 5
integers
if (arr) {
for (int i = 0; i < 5; i++) arr[i] = i * 10; // Assign values
return 0;
}
int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive case
}
int main() {
printf("%d\n", factorial(5)); // Output: 120
return 0;
}