C-specific code examples

pull/1/head
EmaMaker 2018-12-27 18:31:37 +01:00 committed by GitHub
parent 4d79855381
commit f66c354471
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 68 additions and 0 deletions

4
char to int.c Normal file
View File

@ -0,0 +1,4 @@
/*char to int (48 is the value of '0' in the ascii table)
since casting char to int returns an int with the value of the char inside the ascii table (see ascii table), subtracting 48 makes the new int is correspettive in number.
printf("%d", ((int) ('3')) - 48);

4
size of an array.c Normal file
View File

@ -0,0 +1,4 @@
int ciao[3];
printf("%ld", sizeof(ciao) / sizeof(*ciao)); //size in bytes of the array divided by the size in bytes of the type (pointer to the array, or first array of the element)

36
timeout_scanf.c Normal file
View File

@ -0,0 +1,36 @@
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
int value = 0;
struct timeval tmo;
fd_set readfds;
printf("Enter a non-zero number: ");
fflush(stdout);
FD_ZERO(&readfds);
FD_SET(0, &readfds);
tmo.tv_sec = 3;
tmo.tv_usec = 0;
if (select(1, &readfds, NULL, NULL, &tmo) == 0) {
printf("User dont give input");
//return (1);
} else {
scanf("%d", &value);
if (value != 0) {
printf("User input a number");
} else {
printf("User dont give input2");
}
}
printf("boh");
return (0);
}

View File

@ -0,0 +1,24 @@
//This program creates and manages a variable-length array
int length = 1; //first length of the array
int* out = (int*) malloc(length * sizeof(int)); //allocates as much ram as indicated by the length of the array (b) multiplied by the size on an int in Ram. This is actually a pointer to the ram that as been allocated
int* out_copy = out; //now creates a pointer to a copy of the other pointer, that acts as a constant copy
printf("Starting array length: %d\n\tNew value in index 0 is: ", length);
out[0] = 32; //assign a value to the first element
printf("%d\n", out[0]); //prints the new value
length = 2; //now it changes the length
printf("New array length: %d\n", length);
printf("Creating new array with increased length\n");
out = (int*) malloc(length * sizeof(int)); //creates the new array, with the new length
out=out_copy; //copies the pointer to the old array into the new one
printf("Longer array has been created and old array value copied into the new one\nNew values are:\n");
out[1] = 33; //adds a variable into the new index that has been created when increasing lenght
printf("\t%d\n", out[0]); //prints the value in the first index (it is still the value instantiated before)
printf("\t%d\n", out[1]); //prints the new value: the array length as increased
free(out_copy);