Friday, August 10, 2012

C Programming Basics : Arrays, Dynamic Memory, IO, and more

These are some notes from a java/c class I took 
  • Arrays, pointers, strings, dynamic memory
    • Java doesn't let you pass by reference or work with the original object by calling a function with a pointer
    • c takes pointers and lets you edit what that pointer is referencing
    • In c, swap(&a[0],&a[1]) is the same as swap(a,a+1)
    • char ca[3] = "abc" is not a string
    • Uninitialized spaces are set to nul: char ca[4] = {'a','b','c'}// a string
    • You cannot assign to array (all at once) except at initialization in definition
    • char * cp = "abc"; //string literal (you cannot change)
    • strlen() does not count the nul character
    • string functions
      • strcat
      • strncat
      • strcmp
      • strncmp
      • strcpy
      • strncpy
      • strlen
      • strchr- finds first occurrence of a specified character in a string
      • strrchr-finds last occurrence of a specified character in a string
      • strpbrk-finds first occurrence of any character from a set in a string
      • strtok-parses a string into tokens
    • character functions
      • isalpha
      • isalnum
      • isdigit
      • islower
      • isupper
      • ispunct
      • isspace
      • tolower
      • toupper
    • You can only initialize a character pointer, not any other type
    • The array parameter for a function is always rewritten as a pointer by the compiler, that is void afunc(int[]) is really void afunc(int *)
    • This means that the address is sent, not the contents of the array
    • You can print decimals with printf %.2f
    • To include a pointer in a typedef for a struct typedef struct _test{..} test, *testp; //just use the type testp to mean a pointer
    • You can point to anything with the void pointer, but the void type may only be used with pointers
    • You cannot dereference a void pointer
    • NULL is the null pointer and it's included in stdio.h
    • Without stdio.h you can use zero (for NULL), but make sure you cast to the appropriate pointer type (ie if returning void *, then return (void *)0)
    • To use a void pointer with a function (ie enqueue(queue * q, void * item)) just pass in any pointer
    • for dynamic memory allocation use: malloc(bytes)//returns a char *, so cast
    • malloc() will return NULL if memory could not be allocated
    • memory must be deallocated when using malloc, free(tmp)
    • You can make a while loop for a linked list while(ptr) //means while(ptr !=NULL)
  • Dynamic memory/ I/O
    • memory leaks when it is allocated but not freed
    • memory gets corrupted when it is freed but still in use
    • memory corruption can also occur when program text is overwritten
    • you can use calloc or malloc to define an array of elements
    • calloc - (int *)calloc(n,sizeof(int));
    • Use realloc to reallocate memory (use for array)- wlens = (int*)realloc(wlens,(n+1)sizeof(int))
    • Use memset to initialize an array - memset((char *)(wlens),0,n*sizeof(int))
    • Using the keyword continue in a loop statement (ie for or while) will go to next iteration
    • fgets(buf,101,stdin) -> reads into buf until newline or eof is reached
    • fgets() will return NULL if no characters were read (eof)
    • fgets() places an extra \0 character following the characters it read
    • the scan format %[^:] will print everything but the colon for an input variable (use with sscanf)
    • for instance: sscanf(buf,"%[^:]:%[^:]:%[^:]:%s",lname,fname,id,email) (it will return the number of arguments read)
  • I/O and Search
    • Java input: bufferedreader br = new BufferedReader(new InputStreamReader(System.in));
    • Java scan line: int v = Integer.parseInt(br.readLine())
    • c scan line scanf("%d",&v)
    • scanf will block until one character is pressed until a return
    • Java can have an empty stop with br.readLine(), just do line.length()
    • You could use gets for an empty stop: gets(buf), but this is a dangerous choice
    • scanf returns number of values assigned
    • char variable types can be used as integers, such as being iterator in for loop
    • getchar() - gets one character from stdin
    • putchar() - places one character in stdout
    • You can test whether the input is an int, by converting it to an int then comparing it with the input
    • You can tokenize a sentence with strtok(buf," ")//the second argument is the delimiter
    • Token example: token = strtok(buf," "); while(token !=NULL){printf("%s\n",token); token = strtok(NULL," ");}
    • strtok places a \0 character at the first place it finds a delimiter character, but it changes the original string
    • strtok remembers the last place by using static variables
    • In c you can define pointers to functions: int (*comp)(void *,void*) //a pointer called comp that points to a function that returns int and takes two void* arguments
    • With gdb you can debug a program by setting break points (break n), telling it to run (run), stepping (s)
    • start gdb by specifying the executable
    • const int * x //this means the pointer points to a constant and the data it points to cannot be changed
    • int * const x //constant pointer-- data it points to can be changed
    • You can initialize a struct: struct _data key = {4,(char *)0}; //in one statement
    • When you want sort or search with generic variables, tell the sort/search function what function to use for comparing
    • You can have an array of function pointers: float (*funcs[])(float,float) = {add,sub,mult,div};
    • Call like this: result = funcs[choice-1](x,y)

No comments:

Post a Comment