๐ C Advanced
This page provides an introduction to C typedef, enum, struct, pointers, functions & memory allocation.
Typedefโ
// typedef existing_type new_name;
typedef char String[50];
String name = "This is first line";
printf("%s", name);
Enumโ
typedef enum {
SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4,
THURSDAY = 5, FRIDAY = 6, SATURDAY = 7
}Day;
Day today = SUNDAY;
printf("%d", today); // this will print 1
Structโ
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
typedef struct {
char name[50];
int age;
float gpa;
bool isFullTime;
} Student;
Student student = {"SpongeBob", 30, 2.5, true};
Student emptyStudent = {0};
printf("%s \n", student.name);
printf("%d \n", student.age);
printf("%.2f \n", student.float);
printf("%d\n", student.isFullTime);
printf("%s\n", (student.isFullTime) ? "YES" : "NO");
Pointersโ
Pointers helps avoid wasting memory by allowing you to pass the address of a large data structure instead of copying the entire data.
int age = 25;
printf("%p", &age); //%p stands for pointer: Memory address of variable
// create a pointer
int *pAge = &age;
printf("\n%p", pAge);
Functionsโ
#include <stdio.h>
// By default parameters in function are pass by value:
// i.e. a copy of variable is made and passed to the function
void happyBirthday(char name[]) {
printf("\nHappy Birthday to you!");
printf("\nHappy Birthday to you!");
printf("\nHappy Birthday dear %s!", name);
printf("\nHappy Birthday to you!");
}
// passing variable as a pointer
void happyBirthdayByPointer(char *name[]) {
printf("\nHappy Birthday to you!");
printf("\nHappy Birthday to you!");
printf("\nHappy Birthday dear %s!", *name);
printf("\nHappy Birthday to you!");
}
int main() {
char name[] = "unnamed1";
// by default pass by value
happyBirthday(name);
// pass by reference
happyBirthdayByPointer(&name);
return 0;
}
Fileโ
Write a file
#include <stdio.h>
int main() {
// open a file in write mode
FILE *pFile = fopen("output.txt", "w");
char text[] = "This is first line.\n This is second line.";
if(pFile == NULL) {
printf("Error opening a file");
return 1;
}
fprintf(pFile, "%s", text);
printf("File was written successfully");
// close the file
fclose(pFile);
return 0;
}
Read a file
#include <stdio.h>
int main() {
// open a file in read mode
FILE *pFile = fopen("input.txt", "r");
char buffer[1024] = {0};
if(pFile == NULL) {
printf("Couldn't open a file");
return 1;
}
while(fgets(buffer, sizeof(buffer), pFile) != NULL) {
printf("%s", buffer);
}
// close the file
fclose(pFile);
return 0;
}
Mallocโ
A function in C that dynamically allocates a specified number of bytes in memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int number = 0;
printf("Enter the number of grades");
scanf("%d", &number);
char *grades = malloc(number * sizeof(char));
if(grades == NULL) {
printf("Memory allocation failed!");
return 1;
}
for(int i = 0; i < number; i++) {
printf("\nEnter grade number %d: ", i + 1);
scanf(" %c", &grades[i]);
}
for(int i = 0; i < number; i++) {
printf("%c ", grades[i]);
}
// returning rented space back to operating system.
free(grades);
// avoids dangling pointers
grades = NULL;
return 0;
}
Callocโ
Contiguous allocation. Allocates memory dynamically and sets all allocated bytes to 0. malloc() is faster, but calloc() leads to less bugs.
#include <stdio.h>
int main() {
int number = 0;
printf("Enter the number of players: ");
scanf("%d", &number);
int *scores = calloc(number, sizeof(int));
if(scores == NULL) {
printf("Memory allocation failed!");
return 1;
}
for(int i = 0; i < numbers; i++) {
printf("%d", scores[i]); // prints everything as 0
}
free(scores);
scores = NULL;
return 0;
}
Reallocโ
Reallocates previously allocated memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int number = 0;
printf("Enter the total number of prices: ");
scanf("%d", &number);
float *prices[] = malloc(number * sizeof(float));
if(prices == NULL) {
printf("Memory allocation failed");
return 1;
}
for(int i = 0; i < number; i++) {
printf("\nEnter price number %d: ", i + 1);
scanf("%f", &prices[i]);
}
int newNumber = 0;
printf("\nEnter a new number of prices: ");
scanf("%d", &newNumber);
// use realloc
float *temp = realloc(prices, newNumber * sizeof(float));
if(temp == NULL) {
printf("\nCould not reallocate memory");
}
else {
prices = temp;
}
for(int i = 0; i < number; i++) {
printf("$%.2f: ", prices[i]);
}
free(prices);
prices = NULL;
}