palcodes reads uses now pictures bookmarks

Notes about C ( work in progress )

From the Beej's guide

About

Language

Variable

Functions

Pointers

Array

Strings

Structs

void set_price(struct car *c, float new_price) {
			(*c).price = new_price;  // Works, but is ugly and non-idiomatic :(
		}
		

File I/O

typedef

void Pointer
  • Sometimes it’s useful to have a pointer to a thing that you don’t know the type of.
  • There are basically two use cases for this.
    1. A function is going to operate on something byte-by-byte. For example, memcpy() copies bytes of memory from one pointer to another, but those pointers can point to any type. memcpy() takes advantage of the fact that if you iterate through char*s, you’re iterating through the bytes of an object no matter what type the object is. More on this in the Multibyte Values subsection.
    2. Another function is calling a function you passed to it (a callback), and it’s passing you data. You know the type of the data, but the function calling you doesn’t. So it passes you void*s—’cause it doesn’t know the type—and you convert those to the type you need. The built-in qsort()84 and bsearch()85 use this technique.
  • You can just using number_of_elements * sizeof(type) to define how many elements of what size to be moved, let's say if you are using memcpy().
  • If we didn't have void pointer, we would have had to use function definitions for each of the data type memcpy() functions.
    1. You cannot do pointer arithmetic on a void*.
    2. You cannot dereference a void*.
    3. You cannot use the arrow operator on a void*, since it’s also a dereference. 4. You cannot use array notation on a void*, since it’s also a dereference, as well86
  • Important piece of example code ```c void my_memcpy(void dest, void src, int byte_count) { // Convert voids to chars char s = src, *d = dest;

    // Now that we have char*s, we can dereference and copy them while (byte_count--) {

      *d++ = *s++;
    		

    }

    // Most of these functions return the destination, just in case // that's useful to the caller. return dest; }

  • possible char unsigned size
char type Minimum Maximum
signed char -128 127
unsigned char 0 255