C variables
From wikinotes
Main Types
numbers
// numbers int num = 3; float num = 3.045f; // f is optional, but ensures the value is a float vs double double num = 2.4056; long num = 2.0000; // bigger than doublestrings
// strings char letter = 'A'; // chars use single-quotes char *name = "will"; // Another way to create a string char name[] = "will"; // C does not have the concept of strings, it uses arrays of chars // ending in '\0'char *names[] = {"abc","def"}; // arrays of cstrings require a *arrays
// arrays int num[] = { 1, 2, 3, 4 }; //arraypointers
// pointers void run_function( struct MyStruct mystruct ){ printf("test"); } int *ptr = malloc( sizeof(struct MyStruct) ); // get pointer to struct of type 'MyStruct' run_function( &my_struct );structs
Simple usage of a struct:
struct MyStruct { int a; int b; }; struct MyStruct var; var.a = 5; var.b = 10; print( var.a );Structs do not let you assign variables where they are being defined. The following example provides a workaround, effectively creating a constructor for the struct.
// struct /* * Structs get a little more complicated, because you manually need to * allocate memory, and create your own constructor. * */ struct Person { char *name; int age; int height; int weight; }; struct Person *Person_create( char *name, int age, int height, int weight ){ /* * Creates new struct, and initializes it's attrs. * (basically, this is a constructor for 'Person') */ struct Person *who = malloc( sizeof(struct Person ) ); assert(who != NULL); who->name = strdup(name); // create new copy in memory who->age = age; who->height = height; who->weight = weight; return who; } void Person_destroy(struct Person *who){ /* * Pass ptr 'who' to this function, and * the object will be deleted in memory * */ assert(who != NULL); free(who->name); // delete string separately, it has it's own independent location. } struct Person { char *name; int age; int height; int weight; }; struct Person *will = Person_create( "will" ); // your constructor returns a pointer. Create a pointer to // the variable with the type 'Person'
Format Strings
printf("string: %s", str ); //string printf("char: %c", chr ); //char printf("int: %d", num ); //int printf("ptr: %p", ptr ); //pointer printf("sizeof: %lu", sizeof(my_string) ); //unsigned-long