C Programming
-
String literal
-
In golang it is with the bufio library
- Using the fgets function supplying the string length and the stdin as parameters along with the variable
Size of an array of numbers¶
- Initializing the array and populating it with values
- To print out the length of the array we need to divide the size of it on the first element as the sizeof function returns the size in bytes. int = 4 bytes
Declaring functions before and after main function¶
- In order to call a function before its definition it needs to have prototype declaration before main
Casting and printing addresses of number and pointer¶
void square_num_ptr(int *num);
int main()
{
int mynum = 35;
square_num_ptr(&mynum);
return 0;
}
void square_num_ptr(int *num){
int result = *num * *num;
printf("Square of Number %d is %d\n",*num,result);
printf("Result and Num addresses Result ADDR: %p num ADDR: %p\n",(void*)&result,(void*)num); /* Preferred way is to cast the address %p to (void*)*/
printf("Result and Num addresses Result ADDR: %p num ADDR: %p\n",&result,(void*)num);
return;
passing array pointers to functons does not retain the array's size and it decays . So we must pass the size separately to the function¶
#include <stdio.h>
void arrayList(int *array)
{
for (int i = 0; i < sizeof(array) / sizeof(array[1]); i++)
{
printf("Array Element %d = %d\n", i, array[i]);
}
printf("Size of the array %d\n",sizeof(array) / sizeof(array[1]));
}
int main()
{
int *arrayPtr;
int array[] = {1, 2, 3, 4, 5, 6};
printf("Size of the array is %d\n", sizeof(array[1]));
arrayList(array);
return 0;
}
-
Output will be array size 2 from the function while it has size 24
-
The correct code should be this
#include <stdio.h> void arrayList(int *array,const int size) { for (int i = 0; i < size; i++) { printf("Array Element %d = %d\n", i, array[i]); } } int main() { int *arrayPtr; int array[] = {1, 2, 3, 4, 5, 6}; printf("Size of the array is %d\n", sizeof(array)); arrayList(array,sizeof(array) / sizeof(array[1])); return 0; } -
Output
sum the digits of a 5 digit number using division modulo and regular¶
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n, rem, sum;
printf("Enter a Number\n");
scanf("%d",&n);
while (n != 0)
{
rem = n % 10;
sum = sum + rem;
n = n / 10;
}
printf("The sum is: %d\n",sum);
return 0;
}
Advanced tpics¶
- type def , custom types
- enums
- preprocessor , string concat
- more on void*
- static libraries and shared objects
- macros
- unions
- function pointers
- advanced pointers
- variable arguments to functions ( variadic functions)
- dynamic linking (dlm_open)
- signals, forking and inter-process communication
- threading and concurency
- sockets
- setjump and longjump
- memory management and fragmentation
- interfacing with kernel modules ( drivers and ioctls)
- compiler and linker flags
- advanced use of gdb
- profiling and tracing tools(gprof, dtrace,strace)
- memory debugging tools such as valgrind