Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save raiyansarker/6c06e2a05752c70595e4a7d99e0d9c1a to your computer and use it in GitHub Desktop.

Select an option

Save raiyansarker/6c06e2a05752c70595e4a7d99e0d9c1a to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h> // this is for calloc
typedef struct node {
int x,y;
struct node *next;
} Node;
int main() {
/*
* calloc allocates memory and initializes it
* the allocation happens in heap
*/
Node *head = (Node*)calloc(1, sizeof(Node));
/*
* We're accessing x through pointer, therefore we must use '->' syntax
*/
head->x = 10;
head->y = 15;
head->next = NULL;
printf("%d %d\n", head->x, head->y);
return 0;
}
#include <stdio.h>
void print(int n) {
/*
* This is base case
* triggers when n = 0
*/
if (n < 1) return;
/*
* This is recursively calling itself where n is reducing by one every time
*/
print(n - 1);
printf("%d ", n);
}
int main() {
/*
* This is user defined
*/
int n;
scanf("%d", &n);
print(n);
return 0;
}
#include <stdio.h>
typedef struct node {
int el;
} Node;
int main() {
Node node;
/*
* This is a pointer that holds the memory address of Node
* Therefore it points to the Node instance called node
*/
Node *node_ptr = &node;
node.el = 9;
/*
* This should print out 9 as we've assigned 9 to the el
*/
printf("%d\n", node.el);
/*
* As node_ptr points to the original instance, it should also print 9
*/
printf("%d\n", node_ptr->el);
/*
* This changes the original instance
*/
node.el = 5;
/*
* As it points to the memory and doesn't just hold any value
* changes to the original one reflects when accessing through pointer
* therefore it prints 5 as well
*/
printf("%d\n", node_ptr->el);
return 0;
}
#include <stdio.h>
#include <string.h>
typedef struct book {
char title[50];
char author[50];
char subject[100];
int id;
} Book;
int main() {
Book book1, book2;
/*
* Book 1 details
*/
strcpy(book1.title, "Surrounded by Idiots");
strcpy(book1.author, "Thomas Erikson");
strcpy(book1.subject, "Human Behavior and Personality Analysis");
book1.id = 26012201;
/*
* Book 2 details
*/
strcpy(book2.title, "Life 3.0");
strcpy(book2.author, "Max Tegmark");
strcpy(book2.subject, "Artificial Intelligence and the Future");
book2.id = 26012202;
/*
* Print book 1 info
*/
printf("Book 1 title : %s\n", book1.title);
printf("Book 1 author : %s\n", book1.author);
printf("Book 1 subject : %s\n", book1.subject);
printf("Book 1 id : %d\n", book1.id);
/*
* Print book 2 info
*/
printf("Book 2 title : %s\n", book2.title);
printf("Book 2 author : %s\n", book2.author);
printf("Book 2 subject : %s\n", book2.subject);
printf("Book 2 id : %d\n", book2.id);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment