C

From Omnia
(Redirected from Programming/c)
Jump to navigation Jump to search

C Programming Language

C Programming Language (2nd Edition) (Prentice Hall Software) (Paperback)]

  • Note: The definitive C guide. Has printf("Hello World\n"); original example

C#

Are you looking for C Sharp?

Hello World

Hello world program - Wikipedia

main() {
  printf("hello, world\n");
}


The C Programming Language (book) - Wikipedia

"Perhaps the most famous example program from the book is its "hello world" program, which just prints out the text "hello, world" to the terminal, as an illustration of a minimal working C program. Numerous texts since then have followed that convention for introducing a programming language."

gcc

See gcc

Code

Hello World

#include <stdio.h>

int main() {
  printf("Hello World\n");
  return 0;
}

Variables

int i = 1;
float f = 1.0;
char c = 'a';
char s[] = "Hello";
char *p = "Hi";

Print

#include <stdio.h>
printf("int:%d  float:%.2f  char:%c  string:%s  string:%s", i, f, c, s, p);

Parameters

int main(int argc, char* argv[]) {
	int i;
	printf("CMD Args: %d\n", argc);
	for(i = 0 ; i < argc ; i++)
		printf("CMD Arg %d = %s\n", i, argv[i]);  // 0 = ./test
}

Array

Basic int array, initialization and length

#include <stdio.h>

int main() {
	// won't work for dymanic allocated memory
	#define ARRAY_LENGTH(x)  (sizeof(x) / sizeof(x[0]))
	
	int int_array[10];// = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        // int int_array[10] = { 0 }; // all elements 0
	// int array_length = sizeof(int_array) / sizeof(int_array[0]);
	int array_length = ARRAY_LENGTH(int_array);
	int i;
	
	for (i = 0 ; i < array_length ; i++) 
		int_array[i] = i;
	
	// 40, 4, 10
	printf("total length:%d,  int size:%d,  array length:%d\n", sizeof(int_array), sizeof(int_array[0]), array_length);
	for (i = 0 ; i < array_length ; i++)
		printf("%d = %d\n", i, int_array[i]);
}

Note: Arrays are passed as points to functions (Pass by Reference), so modifying an array within a function will modify the original.

Basic char array, initialization and length

#include <stdio.h>

#define ARRAY_LENGTH(x)  (sizeof(x) / sizeof(x[0]))

int ord(char c) { return (unsigned char)c; }
char chr(int n) { return (unsigned char)n; }

int main() {
	int i;
	
	// SEVERAL WAYS TO INITIALIZE:
	
	//char char_array[4] = {'O', 'O', 'O', '\0'};
	
	//char char_array[4] = "OOO";  // don't forget ending \0
	
	//char char_array[] = "OOO";  // size is 4 for \0
	
	//char char_array[3];
	
	//for (i = 0 ; i < ARRAY_LENGTH(char_array) ; i++) 
	//	char_array[i] = 'O';
	
	//char char_array[10] = { 0 }; // all elements 0
	
	//char char_array[10] = {'O', 'O'};  // auto fills rest with \0, how nice, but can this be trusted?
	
	char char_array[10] = {[0 ... 9] = 'X'};  // All 'X'
	
	
	// int array_length = sizeof(char_array) / sizeof(char_array[0]);
	int array_length = ARRAY_LENGTH(char_array);
	
	
	// 40, 1, 4
	printf("total length:%d,  char size:%d,  array length:%d\n", sizeof(char_array), sizeof(char_array[0]), array_length);
	for (i = 0 ; i < array_length ; i++)
		printf("%d = %c [%d][%d]\n", i, char_array[i], char_array[i], ord(char_array[i]));
}

References:

Random

FAQ > Generate random numbers? - Cprogramming.com [1]

#include <stdio.h>  
#include <stdlib.h>  
#include <time.h>  

int main(void)
{
  int i;
  srand(time(NULL));
  i = rand();
  printf ("Your random number is %d\n", i);  
  printf ("This compiler can generate random numbers from 0 to %d\n", RAND_MAX);
  return(0);
}

Get number between two numbers:

/*
   * Formula:  
   *    rand() % N   <- To get a number between 0 - N-1
   *    Then add the result to min, giving you 
   *    a random number between min - max.
   */  
  rc = (rand() % (max - min + 1) + min);

Pointers

Simple int pointer:

void mod_ptr(int *mptr) {
	printf("%d\n", *mptr);  // 3

	*mptr = 4;
	printf("%d\n", *mptr);  // 4
	
	int t = 5;
	*mptr = t;
	printf("%d\n", *mptr);  // 5
}

int main() {
	int *ptr;
	*ptr = 1;
	printf("%d\n", *ptr);  // 1
	
	int tmp_num = 2;
	*ptr = tmp_num;  // get value
	printf("%d\n", *ptr);  // 2

	int tmp_num = 2;
	ptr = &tmp_num;  // get address
	printf("%d\n", *ptr);  // 2

	*ptr = 3;
	mod_ptr(ptr);
	printf("%d\n", *ptr);  // 5

	int n;
	n = *ptr;
	printf("%d\n", n);  // 5
}


References:

Function Pointers

References:

C for C++ Programmers

Source: C for C++ Programmers

Hello World

#include <stdio.h>
int main() {
  printf("Hello World");
}

Output

printf("the variable 'i' is: %d", i);
  sequence    type   : produces

  %d or %i  - int    : signed decimal notation
  %s        - char * : prints characters until the null character is reached
  %x        - int    : hexidecimal notation
  %p        - void * : prints as a pointer 
C++   C
cin   stdin
cout  stdout
cerr  stderr
int fputs(const char *str, FILE *stream);
if ( (fputs("Hello world", stdout)) == EOF) {
  fprint(stderr, "Whoops, something went wrong");
}

Input

Input is a bit trickier. For reading an entire line you'll probably want to use fgets(). Here's the prototype:

 char *fgets(char *buffer, int size, FILE *stream);

fgets() reads up to size-1 characters from stream and stores them in buffer. fgets() stores the null character ('\0') after the last character read into the buffer and returns 'buffer' if everything works fine, or NULL on error or end of file. Here's an example:

 char *cptr;
 char buffer[256];
 
 printf("Enter some stuff:\n");
 cptr = fgets(buffer, 256, stdin);
 if(cptr != NULL) {
   printf("You typed : %s\n", cptr);
 }

Command Line Arguments

#include <stdio.h>

int main(int argc, char *argv[]) {
  // argc - count of parameters, include program name
  // argv - array of arguments, argv[0] is program name
  if(argc == 2) {
    printf("Hello %s\n", argv[0]);
  } else {
    printf("Usage: %s [name]\n", argv[0]);
  }
}

Memory Allocation

 void * malloc(int nbytes)
 /* We're going to allocate enough space for an integer 
    and assign 5 to that memory location */
 int *foo;
 /* malloc call: note the cast of the return value
    from a void * to the appropriate pointer type */
 foo = (int *) malloc(sizeof(int));  
 *foo = 5;
 /* Here we're allocating space for 5 integers */
 int *foo;
 foo = (int *) malloc(sizeof(int) * 5);
 foo[0] = 17;
 foo[4] = 22;
 void free(void *);
 free(foo);
#define SIZE_N 1024*1024 // 1M
#define SIZE_M 256*37

...
  char *ptr;
  if( ( ptr = calloc( SIZE_N, SIZE_M ) ) == NULL ) {
    printf("Error allocating memory!\n");
    exit(1);
  }
  ...
  free(ptr);

Constants

 #define MAX_LEN 1024
 #define NUM_CALLS 20

structs

 struct point {
   int x;
   int y;
 };

acceptable usage:

 struct point p;
 p.x = 0;
 p.y = 0;

preferred usage:

 struct point *p;
 p = (struct point *) malloc(sizeof(struct point));
 p->x = 0;
 p->y = 0;

remove struct repetition with typedef:

 typdef struct point Point;
 Point *p;
 p = (Point *) malloc(sizeof(Point);
 p->x = 0;

Libraries

 #include <stdlib.h>
 #include <string.h>

Notes

printf formatting

%[flags][min field width][precision][length]conversion specifier
  -----  ---------------  ---------  ------ -------------------
   \             #,*        .#, .*     /             \
    \                                 /               \
   #,0,-,+, ,',I                 hh,h,l,ll,j,z,L    c,d,u,x,X,e,f,g,s,p,%</b>
   -------------                 ---------------    -----------------------
   # | Alternate,                 hh | char,           c | unsigned char,
   0 | zero pad,                   h | short,          d | signed int,
   - | left align,                 l | long,           u | unsigned int,
   + | explicit + - sign,         ll | long long,      x | unsigned hex int,
     | space for + sign,           j | [u]intmax_t,    X | unsigned HEX int,
   ' | locale thousands grouping,  z | size_t,         e | [-]d.ddde±dd double,
   I | Use locale's alt digits     t | ptrdiff_t,      E | [-]d.dddE±dd double,
                                   L | long double,  ---------=====
   if no precision   => 6 decimal places            /  f | [-]d.ddd double,
   if precision = 0  => 0 decimal places      _____/   g | e|f as appropriate,
   if precision = #  => # decimal places               G | E|F as appropriate,
   if flag = #       => always show decimal point      s | string,
                                             ..............------
                                            /          p | pointer,
   if precision      => max field width    /           % | %

Source: printf format specifications quick reference

More at: printf - C++ Reference

malloc vs calloc

Conceptually, calloc works like this: [2]

void *calloc ( size_t n, size_t size ) {
  void *mem = malloc ( n * size );
  memset ( mem, 0, n * size );
  return mem;
}

Array of pointers

Array of pointers: [3]

#include <stdio.h>
#include <conio.h>
void main() {
  clrscr();
  char *array[2];
  array[0]="Hello";
  array[1]="World";
  printf("The Array of String is = %s,%s\n", array[0], array[1]);
  getch();
}

My Code

fork

if(fork())
	printf("I am the parent!"); /* A non-zero indicates the parent process */
else
	printf("I am the child!"); /* A zero indicates the child process */

parameters

signals

Bloat Memory

#include <stdlib.h>
#include <stdio.h>

#define BLOAT_ARRAY_SIZE 100000  // 10K
#define BLOAT_SIZE 1024*1024     // 1MB

typedef struct {
  char bloat[BLOAT_SIZE];
} bloat_struct;

int main() {
  bloat_struct *bloat_array[BLOAT_ARRAY_SIZE];  // array of bloated structures

  printf("Bloat Array Size: %d\n", BLOAT_ARRAY_SIZE);
  printf("Bloat Size: %d\n", BLOAT_SIZE);

  int i, j;  // loop variables
  for( i=0 ; i<BLOAT_ARRAY_SIZE ; i++ ) {

    // allocate memory for bloated structure
    //if( ( bloat_array[i] = (bloat_struct *) malloc( sizeof(bloat_struct) ) ) == NULL )
    if( ( bloat_array[i] = (bloat_struct *) calloc( sizeof(bloat_struct), 1 ) ) == NULL )
      printf("Error allocating bloat: #%d\n", i);

    // use allocated memory
    //for( j = 0 ; j<BLOAT_ARRAY_SIZE ; j++ )
    //      bloat_array[i]->bloat[j] = '1';
  }

  printf("Memory has been consumed to %d * %d = %.0f bytes.\n",
    BLOAT_SIZE, BLOAT_ARRAY_SIZE, (double) BLOAT_SIZE * BLOAT_ARRAY_SIZE);
  printf("Press enter to free the memory . . . ");

  char *input;
  char buff[256];
  input = fgets(buff, sizeof(buff), stdin);

  // free allocated memory
  for( i=0 ; i<BLOAT_ARRAY_SIZE ; i++ ) {
    free(bloat_array[i]);
  }

  return 0;
}
Memory consumed: 1073741824

Press enter to free the memory . . .
[root@adaptecweb ~]# gcc eatmem2.c -o eatmem2 ; if [ $? = 0 ] ; then ./eatmem2 ; fi
#include <stdio.h>
#include <stdlib.h>

#define BLOAT_ARRAY_SIZE 1024           // 1K
#define BLOAT_SIZE 1024*1024            // 1MB

int main() {
        char *bloat_array[BLOAT_ARRAY_SIZE];    // array of pointers

        char buff[1024];        // buffer for readline

        printf("Object count: %d\n", BLOAT_ARRAY_SIZE);
        printf("Object size:: %d\n", BLOAT_SIZE);
        printf("Memory consumed: %.0f\n", (double) BLOAT_SIZE * BLOAT_ARRAY_SIZE);
        printf("\n");

        int i, j;       // loop variables
                if( ( bloat_array[0] = calloc( BLOAT_SIZE, BLOAT_ARRAY_SIZE ) ) == NULL )
                        printf("Error!");
        /*
for( i=0 ; i<BLOAT_ARRAY_SIZE ; i++ ) {
                // allocate and zero fill memory for each object
                if( ( bloat_array[i] = calloc( BLOAT_SIZE, 1 ) ) == NULL )
                        printf("Error allocating memory! (#%d)\n", i);
        }
*/
        printf("Press enter to free the memory . . . ");
        fgets(buff, sizeof(buff), stdin);

        free(bloat_array[0]);
        return 0;

        // free allocated memory
        for( i=0 ; i<BLOAT_ARRAY_SIZE ; i++ ) {
                free(bloat_array[i]);
        }

        //printf("Press enter to free the exit . . . ");
        //fgets(buff, sizeof(buff), stdin);

        return 0;
}
#include <stdio.h>
#include <stdlib.h>

#define BLOAT_ARRAY_SIZE 1024           // 1K
#define BLOAT_SIZE 1024*1024            // 1MB

int main() {
        char *bloat_array[BLOAT_ARRAY_SIZE];    // array of pointers

        char buff[1024];        // buffer for readline

        printf("Object count: %d\n", BLOAT_ARRAY_SIZE);
        printf("Object size:: %d\n", BLOAT_SIZE);
        printf("Memory consumed: %.0f\n", (double) BLOAT_SIZE * BLOAT_ARRAY_SIZE);
        printf("\n");

        int i, j;       // loop variables
        for( i=0 ; i<BLOAT_ARRAY_SIZE ; i++ ) {
                // allocate and zero fill memory for each object
                if( ( bloat_array[i] = calloc( BLOAT_SIZE, 1 ) ) == NULL )
                        printf("Error allocating memory! (#%d)\n", i);
        }

        printf("Press enter to free the memory . . . ");
        fgets(buff, sizeof(buff), stdin);

        // free allocated memory
        for( i=0 ; i<BLOAT_ARRAY_SIZE ; i++ ) {
                free(bloat_array[i]);
        }

        //printf("Press enter to free the exit . . . ");
        //fgets(buff, sizeof(buff), stdin);

        return 0;
}
#include <stdio.h>
#include <stdlib.h>

#define SIZE_N 1024*1024 // 1M
#define SIZE_M 126*12

int main() {
        char *ptr;

        printf("Allocating %.0f bytes.\n", (double) SIZE_N * SIZE_M);
        if( ( ptr = calloc( SIZE_N, SIZE_M ) ) == NULL ) {
                printf("Error allocating memory!\n");
                exit(1);
        }

        printf("Press enter to free the memory . . . ");
        char buff[1024];        // buffer for readline
        fgets(buff, sizeof(buff), stdin);

        // free allocated memory
        free(ptr);

        return 0;
}

keywords