C Libraries. Using GLib. Ph. D. Eng. Lucjan Miękina upel.agh.edu.pl/wimir/login/ Department of Robotics and Mechatronics 1/31

Size: px
Start display at page:

Download "C Libraries. Using GLib. Ph. D. Eng. Lucjan Miękina upel.agh.edu.pl/wimir/login/ Department of Robotics and Mechatronics 1/31"

Transcription

1 1/31 C Libraries Using GLib Ph. D. Eng. Lucjan Miękina upel.agh.edu.pl/wimir/login/ Department of Robotics and Mechatronics January 10, 2017

2 2/31 Programming in C External libraries - GLib If you re writing non-trivial code in C, you ll find that it s pretty short on complex data structures. There are lots of simple ways to store data, of course: The primitive types ints, floats, chars, and so forth. enums, which can hold a series of symbolic names for integers. The array, which is C s most flexible data structure Stuctures, capable of holding arbitrary set of data, each of (possibly) different types. Typical programming tasks require more data structures. With C, however, there s no built-in container support; you either have to roll your own or use someone else s data structure library. Fortunately, there is GLib, which is an excellent, free, open source library that fills this need. It contains most of the standard data structures and many of the utilities that you need to effectively manipulate data in your programs. And it s been around since 1996, so it s been thoroughly tested with a lot of useful functionality added along the way. GLib is a low-level library that provides many useful definitions and functions, including definitions for basic types and their limits, standard macros, type conversions, byte order, memory allocation, warnings and assertions, message logging, timers, string utilities, hook functions, a lexical scanner, dynamic loading of modules, and automatic string completion. Real-world GLib usage: GNOME, GIMP, Evolution, etc.

3 3/31 GLib data structures GLib defines a number of data structures (and their related operations), including: Memory chunks Doubly-linked lists Singly-linked lists Hash tables Strings which can grow dynamically String chunks - groups of strings Arrays which can grow in size as elements are added Balanced binary trees N-ary trees Quarks - a two-way association of a string and a unique integer identifier Keyed data lists - lists of data elements accessible by a string or integer id (maps) Relations and tuples - tables of data which can be indexed on any number of fields Caches

4 4/31 Compiling GLib programs Since the programs use GLib, you need to tell the compiler where the GLib header files and libraries are so it can resolve the GLib-defined types. Here s a simple program: 1 #include <glib.h> 2 int main(int argc, char** argv) { 3 GList* list = 0; 4 list = g_list_append(list, "Hello!"); 5 list = g_list_prepend(list, "Goodbye!"); 6 printf("the first item is: '%s'\n", g_list_first(list)->data); 7 return 0; 8 } You can compile this program by invoking GCC like this: $ gcc -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -lglib-2.0 -o ex-compile ex-compile.c Note that you need to know paths to header files on your development machine. More portable way of doing this involves the use of pkg-config tool: $ gcc `pkg-config --cflags glib-2.0` main.c `pkg-config --libs glib-2.0` And then we run it to see the expected output: $./ex-compile The first item is 'Goodbye!'

5 5/31 GLib - Singly-linked lists Perhaps the simplest container in GLib is the singly-linked list; named GSList. Definition: A singly-linked list is a series of data items that are linked together so that you can navigate from one data item to the next. It s called a singly-linked list because there s only a single link between the items. So, you can only move "forward" through the list, but you can t move forward and then back up. Structure: Every time you append an item to the list, a new GSList structure is created. This GSList structure consists of a data item and a pointer. The previous end of the list is then pointed to this new node, which means that now the new node is at the end of the list. NOTICE: The entire structure is called a GSList and each node is a GSList structure as well. Conceptually, a list is just a sequence of lists that are each one item long.

6 6/31 GLib - Singly-linked lists - properties Having a list of items linked together has some usage implications: Determining the length of the list is an O(n) operation; you can t figure out how long the list is unless you count each item. Adding to the front of the list is fast (an O(1) operation) since the list is not a fixed length and doesn t need to be rebuilt once it exceeds a threshold. Finding an item is an O(n) operation since you need to do a linear search over the entire list until you find what you re looking for. Adding an item to the end of the list is also an O(n) operation since to get to the end you need to start at the beginning and iterate until you reach the end of the list. NOTICE: A GSList can hold two basic types of data: integers or pointers. But this really means that you can put pretty much anything in a GSList. For example, if you wanted a GSList of the "short" data type, you could just put pointers to the shorts in the GSList.

7 7/31 GLib - Singly-linked lists - creating, adding, and destroying The following code initializes a GSList, adds two items to it, removes the first item, prints out the list s length, and frees it: 3 int main(int argc, char** argv) { 4 GSList* list = 0; 5 list = g_slist_append(list, "second"); 6 list = g_slist_prepend(list, "first"); 7 printf("the list is now %d items long\n", g_slist_length(list)); 8 list = g_slist_remove(list, "first"); 9 printf("the list is now %d items long\n", g_slist_length(list)); 10 g_slist_free(list); 11 return 0; 12 } 1 The list is now 2 items long 2 The list is now 1 items long

8 8/31 GLib - Singly-linked lists - the last, nth and nth_data functions Once some items are in a GSList, you can pick out them in various ways. Here are some examples, with explanations in the accompanying printf statements: 3 int main(int argc, char** argv) { 4 GSList* list = 0; 5 list = g_slist_append(list, "first"); 6 list = g_slist_append(list, "second"); 7 list = g_slist_append(list, "third"); 8 printf("the last item is '%s'\n", 9 g_slist_last(list)->data); 10 printf("the item at index '1' is '%s'\n", 11 g_slist_nth(list, 1)->data); 12 printf("now the item at index '1' the easy way: '%s'\n", 13 g_slist_nth_data(list, 1)); 14 printf("and the 'next' item after first item is '%s'\n", 15 g_slist_next(list)->data); 16 g_slist_free(list); 17 return 0; 18 } 1 The last item is 'third' 2 The item at index '1' is 'second' 3 Now the item at index '1' the easy way: 'second' 4 And the 'next' item after first item is 'second'

9 9/31 GLib - Singly-linked lists - Working with user-defined types So far we ve been working with strings; that is, we ve been putting pointers to characters in the GSList. In the code sample below, we define a Person struct and push a few instances of that into a GSList: 1 #include <stdlib.h> 2 #include <stdio.h> 3 #include <glib.h> 4 typedef struct { 5 char* name; 6 int age; 7 } Person; 8 int main(int argc, char** argv) { 9 GSList* list = NULL; 10 Person* tom = (Person*)malloc(sizeof(Person)); 11 tom->name = "Tom"; tom->age = 40; 12 list = g_slist_append(list, tom); 13 // allocate memory for one Person 14 Person* luc = g_new(person, 1); 15 luc->name = "Luc"; luc->age = 45; 16 list = g_slist_append(list, luc); 17 printf("tom is '%d'\n", 18 ((Person*)list->data)->age); 19 printf("the last Person is: '%s'\n", 20 ((Person*)g_slist_last(list)->data)->name); 21 g_slist_free(list); free(tom); g_free(luc); 22 return 0; 23 } 1 Tom is '40' 2 The last Person is: 'Luc'

10 10/31 GLib - Singly-linked lists - Simple iterating A straightforward way of iterating over the contents of a GSList is based on iterators. The iterator object is just a variable declared as a pointer to a GSList structure. Since a singly-linked list is a series of GSList structs, the iterator and the list should be of the same type. Note also that this code uses a common GLib usage idiom; it declares the iterator variable at the same time that it declares the GSList itself. 3 int main(int argc, char** argv) { 4 GSList* list = NULL; 5 GSList* iterator = NULL; 6 list = g_slist_append(list, "one"); 7 list = g_slist_append(list, "two"); 8 list = g_slist_append(list, "three"); 9 for (iterator = list; iterator; iterator = iterator->next) 10 printf("current item: '%s'\n", iterator->data); 11 g_slist_free(list); 12 return 0; 13 } 1 Current item: 'one' 2 Current item: 'two' 3 Current item: 'three'

11 11/31 GLib - Singly-linked lists - Advanced iteration with functions Another way to iterate over a GSList is to use the g_slist_foreach function and supply a function to be called for each item in the list. 3 void iterator_2(gpointer item, gpointer prefix) { 4 printf(" %s %s\n", (char*)prefix, (char*)item); 5 } 6 void iterator_1(gpointer item) { 7 printf(" - %s\n", (char*)item); 8 } 9 int main(int argc, char** argv) { 10 GSList* list = 0; 11 list = g_slist_append(list, g_strdup("one")); 12 list = g_slist_append(list, g_strdup("two")); 13 list = g_slist_append(list, g_strdup("three")); 14 printf("iterate with iterator_2:\n"); 15 g_slist_foreach(list, iterator_2, "->"); 16 printf("iterate with iterator_1:\n"); 17 g_slist_foreach(list, (GFunc)iterator_1, 0); 18 printf("freeing"); 19 g_slist_foreach(list, (GFunc)g_free, 0); 20 g_slist_free(list); 21 return 0; 22 } 1 Iterate with iterator_2: 2 -> one 3 -> two 4 -> three 5 Iterate with iterator_1: 6 - one 7 - two 8 - three 9 Freeing

12 12/31 GLib - Singly-linked lists - Finding an element To find an element in a GSList, you can use g_slist_find if you already have the data you re looking for and just want to get to that location in the list. Additionally, you can use g_slist_find_custom, which lets you use a function to check each item in the list. Both functions are illustrated below: 3 gint my_finder(gconstpointer el) { 4 return g_ascii_strcasecmp(el, "two"); 5 } 6 int main(int argc, char** argv) { 7 GSList* list = g_slist_append(null, "one"); 8 list = g_slist_append(list, "two"); 9 list = g_slist_append(list, "three"); 10 GSList* el = g_slist_find(list, "two"); 11 printf("expected: 'two', found: '%s'\n", 12 (char*)el->data); 13 el = g_slist_find_custom(list, NULL, 14 (GCompareFunc)my_finder); 15 printf("expected: 'two', found: '%s'\n", 16 (char*)el->data); 17 el = g_slist_find(list, "zero"); 18 printf("expected: 'zero', found: '%s'\n", 19 el? (char*)el->data : "null"); 20 g_slist_free(list); 21 return 0; 22 } 1 Expected: 'two', found: 'two' 2 Expected: 'two', found: 'two' 3 Expected: 'zero', found: 'null'

13 13/31 GLib - Singly-linked lists - Sorting with GCompareFunc You can sort a GSList by supplying a function that knows how to compare the items in that list. The following example shows one way to sort a list of strings: 3 gint my_comparator(gconstpointer item1, gconstpointer item2) { 4 return g_ascii_strcasecmp(item1, item2); 5 } 6 int main(int argc, char** argv) { 7 GSList* list = g_slist_append(null, "Zakopane"); 8 list = g_slist_append(list, "Bochnia"); 9 list = g_slist_append(list, "Narama"); 10 list = g_slist_sort(list, (GCompareFunc)my_comparator); 11 printf("first node: '%s'\n", (char*)list->data); 12 printf(" Last node: '%s'\n", (char*)g_slist_last(list)->data); 13 g_slist_free(list); 14 return 0; 15 } 1 First node: 'Bochnia' 2 Last node: 'Zakopane'

14 14/31 GLib - Doubly-linked lists Doubly-linked lists are much like singly-linked lists, but they contain extra pointers to enable more navigation options; given a node in a doubly-linked list, you can either move forward or backward. This makes them more flexible then singly-linked lists, but it also increases memory usage, so don t use a doubly-linked list unless you re actually going to need this flexibility. GLib contains a doubly-linked list implementation called a GList. Most of the operations in a GList are similar to those in a GSList. Basic operations The example shows the typical GList usage: 1 #include <glib.h> 2 int main(int argc, char** argv) { 3 GList* list = 0; 4 list = g_list_append(list, "Hello!"); 5 list = g_list_prepend(list, "Goodbye!"); 6 printf("the first item is: '%s'\n", g_list_first(list)->data); 7 return 0; 8 } 1 The first item is: 'Goodbye!'

15 15/31 GLib - Doubly-linked lists 3 int main(int argc, char** argv) { 4 GList* list = 0; 5 list = g_list_append(list, "Chammonix "); 6 printf("the first item: '%s'\n", (char*)list->data); 7 list = g_list_insert(list, "Bormio ", 1); 8 printf("the second item: '%s'\n", 9 (char*)((glist*)g_list_next(list))->data); 10 list = g_list_remove(list, "Bormio "); 11 printf("removing 'Bormio', the list has %d item(s)", 12 g_list_length(list)); 13 GList* new_list = g_list_append(null, "Bormio "); 14 list = g_list_concat(list, new_list); 15 printf("\nconcatenation: "); g_list_foreach(list, (GFunc)printf, 0); 16 list = g_list_reverse(list); 17 printf("\nreversing: "); g_list_foreach(list, (GFunc)printf, 0); 18 g_list_free(list); 19 return 0; 20 } 1 The first item: 'Chammonix ' 2 The second item: 'Bormio ' 3 Removing 'Bormio', the list has 1 item(s) 4 Concatenation: Chammonix Bormio 5 Reversing: Bormio Chammonix

16 16/31 GLib - Doubly-linked lists: advanced navigation 3 int main(int argc, char** argv) { 4 GList* list = g_list_append(null, "Bormio "); 5 list = g_list_append(list, "Chammonix "); 6 list = g_list_append(list, "Davos "); 7 printf("items in the list: "); 8 g_list_foreach(list, (GFunc)printf, NULL); 9 GList* end = g_list_last(list); 10 printf("\nthe first item: '%s'", (char*)g_list_first(end)->data); 11 printf("\nthe next-to-last item: '%s'", 12 (char*)((glist*)g_list_previous(end))->data); 13 printf("\nthe next-to-last item: '%s'", 14 (char*)g_list_nth_prev(end, 1)->data); 15 g_list_free(list); 16 return 0; 17 } 1 Items in the list: Bormio Chammonix Davos 2 The first item: 'Bormio ' 3 The next-to-last item: 'Chammonix ' 4 The next-to-last item: 'Chammonix '

17 17/31 GLib - dynamic arrays So far we ve covered two types of ordered collections: GSList and GList. These are rather similar in that they depend on pointers to link from one element to the next item, or in the case of the GList, to the previous item. But there s another type of ordered collection that doesn t use links; instead it works more or less like a C array. Definition: GArray provides an indexed ordered collection of a single type that grows as necessary to accommodate new items, and shrinks when items are removed. Question: What s the advantage of an array over a linked list? Answer: Indexed access. That is, if you want to get the third element in the array, you can simply call a function to retrieve that item in constant time; there s no need to iterate up to that point manually, which would be an O(n) operation. Moreover, an array knows its own size, so to query the size is an O(1) operation rather than O(n) operation.

18 18/31 GLib - dynamic arrays 3 int main(int argc, char** argv) { 4 GArray* a = g_array_new(false, FALSE, sizeof(char*)); 5 char* first = "hi", *second = "my", *third = "friend"; 6 g_array_append_val(a, first); 7 g_array_append_val(a, second); 8 g_array_append_val(a, third); 9 printf("the array has %d elements\n", a->len); 10 printf("the first is: '%s'\n", g_array_index(a, char*, 0)); 11 printf("the third is: '%s'\n", g_array_index(a, char*, 2)); 12 g_array_remove_index(a, 1); 13 printf("the array has %d elements", a->len); 14 g_array_free(a, FALSE); 15 return 0; 16 } 1 The array has 3 elements 2 The first is: 'hi' 3 The third is: 'friend' 4 The array has 2 elements

19 19/31 GLib - dynamic arrays: analyzing the example There are several options to consider when creating a GArray using the g_array_new function. We control the options by the arguments we pass to g_array_new: the first argument indicates whether the array should have a zero element as a terminator the second argument indicates whether new elements in the array should be automatically set to zero, the third argument tells the array the size of datatype it is going to hold. In this case the array is created to hold the type char*; putting anything else in the array would lead to segmentation fault. A GArray is a structure with a member variable len, so to get the size of the array, you can just reference that variable directly; no need for a function call. A GArray grows in powers of two. That is, if a GArray contains four items and you add another, it will internally create another eight-element GArray, copy the four existing elements into it, and then add your new element. This resizing process takes time, so if you know you re going to have a certain number of elements, it s more efficient to create the GArray pre-allocated to the desired size. g_array_append_val is a macro designed so that it does not accept literal values, so you can t call g_array_append_val(a, "some string") Instead, the value needs to be placed in a variable and that variable passed in to g_array_append_val. As a consolation for the inconvenience, g_array_append_val is very fast.

20 20/31 GLib - dynamic arrays: more ways to add data The g_array_append_val function appends a new item (at the end). There are other ways to add/insert data: 3 void print(garray* a) { 4 printf("the array holds: "); 5 int i; 6 for (i = 0; i < a->len; i++) 7 printf("%d ", g_array_index(a, int, i)); 8 printf("\n"); 9 } 10 int main(int argc, char** argv) { 11 GArray* a = g_array_new(false, FALSE, sizeof(int)); 12 printf("appending... "); 13 int x[2] = {4,5}; g_array_append_vals(a, x, 2); print(a); 14 printf("prepending... "); // NOTICE: O(n) operation! 15 int y[2] = {2,3}; g_array_prepend_vals(a, y, 2); print(a); 16 printf("prepending... "); 17 int z = 1; g_array_prepend_val(a, z); print(a); 18 g_array_free(a, FALSE); 19 return 0; 20 } 1 Appending... The array holds: Prepending... The array holds: Prepending... The array holds:

21 21/31 GLib - dynamic arrays: inserting data It s possible to insert data in any place, not only at the beginning or end of GArray: 3 void print(garray* a); // defined in "print.c" 4 int main(int argc, char** argv) { 5 GArray* a = g_array_new(false, FALSE, sizeof(int)); 6 int x[2] = {1,5}; g_array_append_vals(a, x, 2); print(a); 7 printf("inserting single value '2'\n"); 8 int b = 2; g_array_insert_val(a, 1, b); print(a); 9 printf("inserting an array int y[2]\n"); 10 int y[2] = {3,4}; g_array_insert_vals(a, 2, y, 2); print(a); 11 g_array_free(a, FALSE); 12 return 0; 13 } 1 The array holds: Inserting single value '2' 3 The array holds: Inserting an array int y[2] 5 The array holds:

22 22/31 GLib - dynamic arrays: removing data There are 3 ways to remove data from GArray: using the g_array_remove_index and g_array_remove_range functions, that preserve the order of items in GArray using the g_array_remove_index_fast, that may change the ordering. 3 void print(garray* a); // defined in "print.c" 4 int main(int argc, char** argv) { 5 GArray* a = g_array_new(false, FALSE, sizeof(int)); 6 int x[6] = {1,2,3,4,5,6}; 7 g_array_append_vals(a, &x, 6); print(a); 8 printf("removing the first element ---> "); 9 g_array_remove_index(a, 0); print(a); 10 printf("removing two elements > "); 11 g_array_remove_range(a, 0, 2); print(a); 12 printf("fast-remove the 1st element --> "); 13 g_array_remove_index_fast(a, 0); print(a); 14 g_array_free(a, FALSE); 15 return 0; 16 } 1 The array holds: Removing the first element ---> The array holds: Removing two elements > The array holds: Fast-remove the 1st element --> The array holds: 6 5

23 23/31 GLib - dynamic arrays: sorting data Sorting GArray, similarly to sorting GList and GSList, can be done using GCompareFunc, which defines how to compare items in GArray: 3 void print(garray* a); // defined in "print.c" 4 int compare_ints(gpointer a, gpointer b) { 5 int* x = (int*)a; 6 int* y = (int*)b; 7 return *x - *y; 8 } 9 int main(int argc, char** argv) { 10 GArray* a = g_array_new(false, FALSE, sizeof(int)); 11 int x[6] = {2,1,6,5,4,3}; 12 g_array_append_vals(a, x, 6); print(a); 13 printf("sorting\n"); 14 g_array_sort(a, (GCompareFunc)compare_ints); 15 print(a); 16 g_array_free(a, FALSE); 17 return 0; 18 } 1 The array holds: Sorting 3 The array holds:

24 24/31 GLib - dynamic arrays: using arrays of pointers GLib defines a type GPtrArray, which eases the task of managing arrays of pointers. It can help, as we no longer have to specify a type of an item when creating an array, accessing or removing its items. The other properties are similar to GArray: 3 int main(int argc, char** argv) { 4 GPtrArray* a = g_ptr_array_new(); 5 g_ptr_array_add(a, g_strdup("s1 ")); 6 g_ptr_array_add(a, g_strdup("s2 ")); 7 g_ptr_array_add(a, g_strdup("s3 ")); 8 g_ptr_array_add(a, g_strdup("s4 ")); 9 g_ptr_array_add(a, g_strdup("\n")); 10 printf(" GPtrArray holds:\n"); 11 g_ptr_array_foreach(a, (GFunc)printf, 0); 12 printf(" Removing the third element\n"); 13 g_ptr_array_remove_index(a, 2); 14 g_ptr_array_foreach(a, (GFunc)printf, 0); 15 printf(" Removing 2nd & 3rd elements\n"); 16 g_ptr_array_remove_range(a, 1, 2); 17 g_ptr_array_foreach(a, (GFunc)printf, 0); 18 printf("the first el. is: '%s'\n", 19 (char*)g_ptr_array_index(a, 0)); 20 g_ptr_array_free(a, TRUE); 21 return 0; 22 } 1 GPtrArray holds: 2 S1 S2 S3 S4 3 Removing the third element 4 S1 S2 S4 5 Removing 2nd & 3rd elements 6 S1 7 The first el. is: 'S1 '

25 25/31 GLib - dynamic strings GLib provides the structural type GString, which supports strings with a variable length. GString is accompanied by functions with names g_string_* to provide useful operations. 3 int main(int argc, char** argv) { 4 GString* s = g_string_new("string"); 5 printf("%s\n", s->str); 6 s = g_string_append(s, "Append"); 7 printf("%s\n", s->str); 8 GString *c = g_string_new("string"); 9 printf("%s %s %s\n", s->str, 10 g_string_equal(s, c)? "==" : "!=", 11 c->str); 12 s = g_string_prepend(s, "Prepend"); 13 printf("%s\n", s->str); 14 s = g_string_insert(s, 7, "Insert"); 15 printf("%s\n", s->str); 16 g_string_free(s, TRUE); 17 g_string_free(c, TRUE); 18 return 0; 19 } 1 String 2 StringAppend 3 StringAppend!= String 4 PrependStringAppend 5 PrependInsertStringAppend

26 26/31 GLib - hash tables So far this tutorial has covered only ordered containers in which items inserted in the container in a certain order stayed that way. Another type of container is a hash table, also known as a map, associative array, or a dictionary. Just as a language dictionary associates a word with a definition, hash tables use a key to uniquely identify a value. Hash tables can perform insertion, lookup, and remove operations on a key very quickly; in fact, with proper usage, these can all be constant time that is, O(1) operations. That s much better than looking up or removing an item from an ordered list, an O(n) operation. Hash tables perform operations quickly because they use a hash function to locate keys. Hash function A hash function takes a key and calculates a unique value, called a hash, for that key. For example, a hash function could accept a word and return the number of letters in that word as the hash. That would be, however, a bad hash function because both fiddle and faddle would hash to the same value.

27 27/31 GLib - hash tables: basic operations 3 int main(int argc, char** argv) { 4 GHashTable* hash = g_hash_table_new(g_str_hash, g_str_equal); 5 g_hash_table_insert(hash, "Poland", "Warsaw"); 6 g_hash_table_insert(hash, "Chech Republic", "Prague"); 7 g_hash_table_insert(hash, "Germany", "Berlin"); 8 printf("there are %d keys in the hash\n", g_hash_table_size(hash)); 9 printf("the capital of Poland is %s\n", 10 (char*)g_hash_table_lookup(hash, "Poland")); 11 gboolean found = g_hash_table_remove(hash, "Chech Republic"); 12 printf("the value 'Chech Republic' was %sfound and removed\n", 13 found? "" : "not "); 14 g_hash_table_destroy(hash); 15 return 0; 16 } 1 There are 3 keys in the hash 2 The capital of Poland is Warsaw 3 The value 'Chech Republic' was found and removed

28 28/31 GLib - hash tables: iterating Sometimes you need to iterate over all the key/value pairs. Here s how to do that using g_hash_table_foreach: 3 void iterator(gpointer key, gpointer value, gpointer user_data) { 4 printf(user_data, *(gint*)key, value); 5 } 6 int main(int argc, char** argv) { 7 GHashTable* hash = g_hash_table_new(g_int_hash, g_int_equal); 8 int k_one = 1, k_two=2, k_three = 3; // keys 9 g_hash_table_insert(hash, &k_one, "one"); 10 g_hash_table_insert(hash, &k_two, "four"); 11 g_hash_table_insert(hash, &k_three, "nine"); 12 g_hash_table_foreach(hash, (GHFunc)iterator, "The square of %d is %s\n"); 13 g_hash_table_destroy(hash); 14 return 0; 15 } 1 The square of 1 is one 2 The square of 2 is four 3 The square of 3 is nine

29 29/31 GLib - hash tables: finding an item To find a specific value, use the g_hash_table_find function. This function lets you look at each key/value pair until you locate the one you want. 3 void value_destroyed(gpointer data) { 4 printf("got a value destroy call for %d\n", GPOINTER_TO_INT(data)); 5 } 6 gboolean finder(gpointer key, gpointer value, gpointer user_data) { 7 return (GPOINTER_TO_INT(key) + GPOINTER_TO_INT(value)) == 6; 8 } 9 int main(int argc, char** argv) { 10 GHashTable* hash = g_hash_table_new_full(g_direct_hash, g_direct_equal, 11 NULL, (GDestroyNotify)value_destroyed); 12 g_hash_table_insert(hash, GINT_TO_POINTER(1), GINT_TO_POINTER(1)); 13 g_hash_table_insert(hash, GINT_TO_POINTER(2), GINT_TO_POINTER(4)); 14 g_hash_table_insert(hash, GINT_TO_POINTER(3), GINT_TO_POINTER(9)); 15 gpointer item_ptr = g_hash_table_find(hash, (GHRFunc)finder, NULL); 16 gint item = GPOINTER_TO_INT(item_ptr); 17 printf("item=%d\n", item); 18 g_hash_table_destroy(hash); 19 return 0; 20 } 1 item=4 2 Got a value destroy call for 1 3 Got a value destroy call for 4 4 Got a value destroy call for 9

30 30/31 GTK+ - creating a simple signal-based GTK application GTK+ is a toolkit which allows for creating GUI applications with C language. Documentation with examples can be found at: You can compile the program with GCC using: $ gcc `pkg-config --cflags gtk+-3.0` -o Gtk1 main.c `pkg-config --libs gtk #include <gtk/gtk.h> 2 3 static void activate (GtkApplication* app, gpointer user_data) { 4 GtkWidget *window; 5 6 window = gtk_application_window_new (app); 7 gtk_window_set_title (GTK_WINDOW (window), "Window"); 8 gtk_window_set_default_size (GTK_WINDOW (window), 200, 200); 9 gtk_widget_show_all (window); 10 } int main (int argc, char **argv) { 13 GtkApplication *app; 14 int status; app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE); 17 g_signal_connect (app, "activate", G_CALLBACK (activate), NULL); 18 status = g_application_run (G_APPLICATION (app), argc, argv); 19 g_object_unref (app); return status; 22 } Result of running:

31 GTK+ - creating a signal-based GTK application with widgets 1 #include <gtk/gtk.h> Rezultat 2 3 static void print_hello (GtkWidget *widget, gpointer data) { wykonania: 4 g_print ("Hello World\n"); 5 } 6 7 static void activate (GtkApplication *app, gpointer user_data) { 8 GtkWidget *window, *button, *button_box; 9 10 window = gtk_application_window_new (app); 11 gtk_window_set_title (GTK_WINDOW (window), "Window"); 12 gtk_window_set_default_size (GTK_WINDOW (window), 200, 200); button_box = gtk_button_box_new (GTK_ORIENTATION_HORIZONTAL); 15 gtk_container_add (GTK_CONTAINER (window), button_box); button = gtk_button_new_with_label ("Hello World"); 18 g_signal_connect (button, "clicked", G_CALLBACK (print_hello), NULL); 19 g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window); 20 gtk_container_add (GTK_CONTAINER (button_box), button); gtk_widget_show_all (window); 23 } int main (int argc, char **argv) { 26 GtkApplication *app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE); 27 g_signal_connect (app, "activate", G_CALLBACK (activate), NULL); 28 int status = g_application_run (G_APPLICATION (app), argc, argv); 29 g_object_unref (app); return status; 32 } 31/31

Lecture 3. GUI Programming part 1: GTK

Lecture 3. GUI Programming part 1: GTK INTRODUCTION TO DESIGN AUTOMATION Lecture 3. GUI Programming part 1: GTK Guoyong Shi, PhD shiguoyong@ic.sjtu.edu.cn School of Microelectronics Shanghai Jiao Tong University Fall 2010 2010-9-15 Slide 1

More information

Creating GNOME Applications with Glade. Part I: Introduction

Creating GNOME Applications with Glade. Part I: Introduction Creating GNOME Applications with Glade Part I: Introduction Glade 3 Glade 3 is a tool to enable quick and easy development of Uis for the GTK+ toolkit and GNOME desktop environment. User interfaces designed

More information

PRINCIPLES OF OPERATING SYSTEMS

PRINCIPLES OF OPERATING SYSTEMS PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)

More information

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo Compilation #include int main()

More information

Array Initialization

Array Initialization Array Initialization Array declarations can specify initializations for the elements of the array: int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; initializes primes[0] to 2, primes[1] to 3, primes[2]

More information

Procedures, Parameters, Values and Variables. Steven R. Bagley

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

More information

Arrays and Pointers in C. Alan L. Cox

Arrays and Pointers in C. Alan L. Cox Arrays and Pointers in C Alan L. Cox alc@rice.edu Objectives Be able to use arrays, pointers, and strings in C programs Be able to explain the representation of these data types at the machine level, including

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14 BIL 104E Introduction to Scientific and Engineering Computing Lecture 14 Because each C program starts at its main() function, information is usually passed to the main() function via command-line arguments.

More information

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

Armide Documentation. Release Kyle Mayes

Armide Documentation. Release Kyle Mayes Armide Documentation Release 0.3.1 Kyle Mayes December 19, 2014 Contents 1 Introduction 1 1.1 Features.................................................. 1 1.2 License..................................................

More information

Pointers (continued), arrays and strings

Pointers (continued), arrays and strings Pointers (continued), arrays and strings 1 Last week We have seen pointers, e.g. of type char *p with the operators * and & These are tricky to understand, unless you draw pictures 2 Pointer arithmetic

More information

Tutorial 1 C Tutorial: Pointers, Strings, Exec

Tutorial 1 C Tutorial: Pointers, Strings, Exec TCSS 422: Operating Systems Institute of Technology Spring 2017 University of Washington Tacoma http://faculty.washington.edu/wlloyd/courses/tcss422 Tutorial 1 C Tutorial: Pointers, Strings, Exec The purpose

More information

Dynamic memory allocation (malloc)

Dynamic memory allocation (malloc) 1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration

More information

Pointers (continued), arrays and strings

Pointers (continued), arrays and strings Pointers (continued), arrays and strings 1 Last week We have seen pointers, e.g. of type char *p with the operators * and & These are tricky to understand, unless you draw pictures 2 Pointer arithmetic

More information

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( )

Tutorial 1: Introduction to C Computer Architecture and Systems Programming ( ) Systems Group Department of Computer Science ETH Zürich Tutorial 1: Introduction to C Computer Architecture and Systems Programming (252-0061-00) Herbstsemester 2012 Goal Quick introduction to C Enough

More information

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment. Lecture 12 CSE 110 20 July 1992 Today we ll cover the things that you still don t know that you need to know in order to do the assignment. 1 The NULL Pointer For each pointer type, there is one special

More information

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level

More information

Programming with Clutter. Murray Cumming

Programming with Clutter. Murray Cumming Programming with Clutter Murray Cumming Programming with Clutter by Murray Cumming Copyright 2007, 2008 Openismus GmbH We very much appreciate any reports of inaccuracies or other errors in this document.

More information

Algorithms, Data Structures, and Problem Solving

Algorithms, Data Structures, and Problem Solving Algorithms, Data Structures, and Problem Solving Masoumeh Taromirad Hamlstad University DT4002, Fall 2016 Container Concepts containers store data container operations: insertion retrieval removal iteration

More information

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems Deep C Multifile projects Getting it running Data types Typecasting Memory management Pointers Fabián E. Bustamante, Fall 2004 Multifile Projects Give your project a structure Modularized design Reuse

More information

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3 Hello, World! in C Johann Myrkraverk Oskarsson October 23, 2018 Contents 1 The Quintessential Example Program 1 I Printing Text 2 II The Main Function 3 III The Header Files 4 IV Compiling and Running

More information

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C Lecture 1 C primer What we will cover A crash course in the basics of C You should read the K&R C book for lots more details Various details will be exemplified later in the course Outline Overview comparison

More information

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

Maemo Diablo Source code for the LibOSSO RPC examples Training Material

Maemo Diablo Source code for the LibOSSO RPC examples Training Material Maemo Diablo Source code for the LibOSSO RPC examples Training Material February 9, 2009 Contents 1 Source code for the LibOSSO RPC examples 2 1.1 libosso-example-sync/libosso-rpc-sync.c..............

More information

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {

The output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 { Memory A bit is a binary digit, either 0 or 1. A byte is eight bits, and can thus represent 256 unique values, such as 00000000 and 10010110. Computer scientists often think in terms of hexadecimal, rather

More information

Question 1. [15 marks]

Question 1. [15 marks] Note to Students: This file contains sample solutions to the term test together with the marking scheme and comments for each question. Please read the solutions and the marking schemes and comments carefully.

More information

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14 COSC 2P91 Introduction Part Deux Week 1b Brock University Brock University (Week 1b) Introduction Part Deux 1 / 14 Source Files Like most other compiled languages, we ll be dealing with a few different

More information

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

More information

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee.

Midterm Exam Nov 8th, COMS W3157 Advanced Programming Columbia University Fall Instructor: Jae Woo Lee. Midterm Exam Nov 8th, 2012 COMS W3157 Advanced Programming Columbia University Fall 2012 Instructor: Jae Woo Lee About this exam: - There are 4 problems totaling 100 points: problem 1: 30 points problem

More information

Computer Systems Assignment 2: Fork and Threads Package

Computer Systems Assignment 2: Fork and Threads Package Autumn Term 2018 Distributed Computing Computer Systems Assignment 2: Fork and Threads Package Assigned on: October 5, 2018 Due by: October 12, 2018 1 Understanding fork() and exec() Creating new processes

More information

Programming. Lists, Stacks, Queues

Programming. Lists, Stacks, Queues Programming Lists, Stacks, Queues Summary Linked lists Create and insert elements Iterate over all elements of the list Remove elements Doubly Linked Lists Circular Linked Lists Stacks Operations and implementation

More information

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ. C BOOTCAMP DAY 2 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Pointers 2 Pointers Pointers are an address in memory Includes variable addresses,

More information

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019 Hacking in C Pointers Radboud University, Nijmegen, The Netherlands Spring 2019 Allocation of multiple variables Consider the program main(){ char x; int i; short s; char y;... } What will the layout of

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable. CMPS 12M Introduction to Data Structures Lab Lab Assignment 3 The purpose of this lab assignment is to introduce the C programming language, including standard input-output functions, command line arguments,

More information

OO for GUI Design (contd.) Questions:

OO for GUI Design (contd.) Questions: OO for GUI Design (contd.) Questions: 1 1. What is a window manager and what are its responsibilities? 2 2. How would you define an event in the context of GUI programming? 3 3. What is the first thing

More information

CS 0449 Sample Midterm

CS 0449 Sample Midterm Name: CS 0449 Sample Midterm Multiple Choice 1.) Given char *a = Hello ; char *b = World;, which of the following would result in an error? A) strlen(a) B) strcpy(a, b) C) strcmp(a, b) D) strstr(a, b)

More information

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Chapter 2 (Dynamic variable (i.e. pointer), Static variable) Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= &num;

More information

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers

Introduction to C. Robert Escriva. Cornell CS 4411, August 30, Geared toward programmers Introduction to C Geared toward programmers Robert Escriva Slide heritage: Alin Dobra Niranjan Nagarajan Owen Arden Cornell CS 4411, August 30, 2010 1 Why C? 2 A Quick Example 3 Programmer s Responsibilities

More information

Lesson 2: GTK+ Basics

Lesson 2: GTK+ Basics 1 A First GTK+ Program We will begin with a very simple GTK+ program in order to demonstrate some of the key tasks that every GTK+ main program must perform. The program, hello_world.c, is found in many

More information

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world alun@debian:~$ gcc hello.c alun@debian:~$ a.out Hello, world alun@debian:~$ gcc -o hello hello.c alun@debian:~$ hello Hello, world alun@debian:~$ 1 A Quick guide to C for Networks and Operating Systems

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Pointers Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) Pointers February 29, 2012 1

More information

CSE 333 Lecture 6 - data structures

CSE 333 Lecture 6 - data structures CSE 333 Lecture 6 - data structures Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia Exercises: - ex5 is out: clean up the code from section yesterday, split

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers

More information

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0; 1. Short answer questions: (a) Compare the typical contents of a module s header file to the contents of a module s implementation file. Which of these files defines the interface between a module and

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Functions Similar to (static) methods in Java without the class: int f(int a, int

More information

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

ECE264 Spring 2013 Final Exam, April 30, 2013

ECE264 Spring 2013 Final Exam, April 30, 2013 ECE264 Spring 2013 Final Exam, April 30, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing

More information

C PROGRAMMING Lecture 5. 1st semester

C PROGRAMMING Lecture 5. 1st semester C PROGRAMMING Lecture 5 1st semester 2017-2018 Program Address Space The Stack The stack is the place where all local variables are stored a local variable is declared in some scope Example int x; //creates

More information

COMP 2400 UNIX Tools

COMP 2400 UNIX Tools COMP 2400 UNIX Tools Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 GTK+ GTK+ = Gimp Tool Kit, Manipulation Program GIMP = GNU Image Basis for Gnome Written in C, bindings for

More information

Data Structure Series

Data Structure Series Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after

More information

The FFI Reference Manual

The FFI Reference Manual The FFI Reference Manual a Foreign Function Interface (version 0.2) for MIT/GNU Scheme version 9.0.1 2011-09-19 by Matt Birkholz This manual documents FFI 0.2. Copyright c 1986, 1987, 1988, 1989, 1990,

More information

Approximately a Test II CPSC 206

Approximately a Test II CPSC 206 Approximately a Test II CPSC 206 Sometime in history based on Kelly and Pohl Last name, First Name Last 5 digits of ID Write your section number(s): All parts of this exam are required unless plainly and

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Puntatori Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 5, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction to C October

More information

Dynamic memory allocation

Dynamic memory allocation Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes

More information

Compiling and Running a C Program in Unix

Compiling and Running a C Program in Unix CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name

More information

Elementary Data Structures: Part 1: Arrays, Lists. CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington

Elementary Data Structures: Part 1: Arrays, Lists. CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington Elementary Data Structures: Part 1: Arrays, Lists CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1 Basic Types Types like integers, real numbers, characters.

More information

C SCI The X Window System Stewart Weiss

C SCI The X Window System Stewart Weiss The X Window System The X Window System is a networking and display protocol which provides windowing on bitmapped displays. X provides the basic framework for building GUI environments, such as drawing

More information

CSE 333 Lecture 6 - data structures

CSE 333 Lecture 6 - data structures CSE 333 Lecture 6 - data structures Steve Gribble Department of Computer Science & Engineering University of Washington Today s topics: - implementing data structures in C - multi-file C programs - brief

More information

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Bernhard Boser & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic

More information

Programming in C - Part 2

Programming in C - Part 2 Programming in C - Part 2 CPSC 457 Mohammad Reza Zakerinasab May 11, 2016 These slides are forked from slides created by Mike Clark Where to find these slides and related source code? http://goo.gl/k1qixb

More information

High Performance Programming Programming in C part 1

High Performance Programming Programming in C part 1 High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

COP Programming Concepts Spring 1999 CLOSED BOOK Exam #1 100 Points NAME

COP Programming Concepts Spring 1999 CLOSED BOOK Exam #1 100 Points NAME CLOSED BOOK Exam #1 100 Points NAME 1. The following program has (at least) 10 syntax errors. Circle each error. Write the corrected program in the blank space below. 2 points for each error you find.

More information

Lecture Notes on Interfaces

Lecture Notes on Interfaces Lecture Notes on Interfaces 15-122: Principles of Imperative Computation Frank Pfenning Lecture 14 October 16, 2012 1 Introduction The notion of an interface to an implementation of an abstract data type

More information

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

G52CPP C++ Programming Lecture 3. Dr Jason Atkin G52CPP C++ Programming Lecture 3 Dr Jason Atkin E-Mail: jaa@cs.nott.ac.uk 1 Revision so far C/C++ designed for speed, Java for catching errors Java hides a lot of the details (so can C++) Much of C, C++

More information

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong

Week 5, continued. This is CS50. Harvard University. Fall Cheng Gong This is CS50. Harvard University. Fall 2014. Cheng Gong Table of Contents News... 1 Buffer Overflow... 1 Malloc... 6 Linked Lists... 7 Searching... 13 Inserting... 16 Removing... 19 News Good news everyone!

More information

Chapter 11 Introduction to Programming in C

Chapter 11 Introduction to Programming in C Chapter 11 Introduction to Programming in C C: A High-Level Language Gives symbolic names to values don t need to know which register or memory location Provides abstraction of underlying hardware operations

More information

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga C-Programming CSC209: Software Tools and Systems Programming Paul Vrbik University of Toronto Mississauga https://mcs.utm.utoronto.ca/~209/ Adapted from Dan Zingaro s 2015 slides. Week 2.0 1 / 19 What

More information

Memory Corruption 101 From Primitives to Exploit

Memory Corruption 101 From Primitives to Exploit Memory Corruption 101 From Primitives to Exploit Created by Nick Walker @ MWR Infosecurity / @tel0seh What is it? A result of Undefined Behaviour Undefined Behaviour A result of executing computer code

More information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 8 C: Miscellanea Control, Declarations, Preprocessor, printf/scanf 1 The story so far The low-level execution model of a process (one

More information

CS 241 Data Organization Pointers and Arrays

CS 241 Data Organization Pointers and Arrays CS 241 Data Organization Pointers and Arrays Brooke Chenoweth University of New Mexico Fall 2017 Read Kernighan & Richie 6 Structures Pointers A pointer is a variable that contains the address of another

More information

CSE 333 Lecture 5 - data structures & modules

CSE 333 Lecture 5 - data structures & modules CSE 333 Lecture 5 - data structures & modules Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia HW1 out now, due in 2 weeks minus ε. Start early and make steady

More information

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides From Java to C Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides 1 Outline Overview comparison of C and Java Good evening Preprocessor

More information

Dynamic Memory Allocation and Command-line Arguments

Dynamic Memory Allocation and Command-line Arguments Dynamic Memory Allocation and Command-line Arguments CSC209: Software Tools and Systems Programming Furkan Alaca & Paul Vrbik University of Toronto Mississauga https://mcs.utm.utoronto.ca/~209/ Week 3

More information

CSE 333 Lecture 7 - final C details

CSE 333 Lecture 7 - final C details CSE 333 Lecture 7 - final C details Steve Gribble Department of Computer Science & Engineering University of Washington Today s topics: - a few final C details header guards and other preprocessor tricks

More information

Lecture 13 Notes Sets

Lecture 13 Notes Sets Lecture 13 Notes Sets 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, Rob Simmons 1 Introduction In this lecture, we will discuss the data structure of hash tables further and

More information

First of all, it is a variable, just like other variables you studied

First of all, it is a variable, just like other variables you studied Pointers: Basics What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the address (rather than the value)

More information

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3). cs3157: another C lecture (mon-21-feb-2005) C pre-processor (1). today: C pre-processor command-line arguments more on data types and operators: booleans in C logical and bitwise operators type conversion

More information

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables.

Actually, C provides another type of variable which allows us to do just that. These are called dynamic variables. When a program is run, memory space is immediately reserved for the variables defined in the program. This memory space is kept by the variables until the program terminates. These variables are called

More information

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc CS61C L4 C Pointers (1) inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture #4 C Strings, Arrays, & Malloc Albert Chae Instructor 2008-06-26 Review: C Strings A string in C is just an array

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

Understanding Pointers

Understanding Pointers Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture CS 61C: Great Ideas in Computer Architecture Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c And in Conclusion, 2 Processor Control Datapath Components of a Computer PC Registers Arithmetic

More information

Lecture 13 Notes Sets

Lecture 13 Notes Sets Lecture 13 Notes Sets 15-122: Principles of Imperative Computation (Fall 2015) Frank Pfenning, Rob Simmons 1 Introduction In this lecture, we will discuss the data structure of hash tables further and

More information

COMP 2001/2401 Test #1 [out of 80 marks]

COMP 2001/2401 Test #1 [out of 80 marks] COMP 2001/2401 Test #1 [out of 80 marks] Duration: 90 minutes Authorized Memoranda: NONE Note: for all questions, you must show your work! Name: Student#: 1. What exact shell command would you use to:

More information

C Language Summary (Continued)

C Language Summary (Continued) Chris J Michael cmicha1@lsu.edu 11 September 2008 C Language Summary (Continued) Heavily Influenced by the GNU C Reference Manual: http://www.gnu.org/software/gnu-c-manual/ Q/A -Somebody brought up a nice

More information

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz CS 61C: Great Ideas in Computer Architecture Lecture 3: Pointers Krste Asanović & Randy Katz http://inst.eecs.berkeley.edu/~cs61c Agenda Pointers in C Arrays in C This is not on the test Pointer arithmetic

More information

CSE 333 Lecture 2 Memory

CSE 333 Lecture 2 Memory CSE 333 Lecture 2 Memory John Zahorjan Department of Computer Science & Engineering University of Washington Today s goals - some terminology - review of memory resources - reserving memory - type checking

More information

Programming refresher and intro to C programming

Programming refresher and intro to C programming Applied mechatronics Programming refresher and intro to C programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2018 Outline 1 C programming intro 2

More information

Arrays and Memory Management

Arrays and Memory Management Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 7: Introduction to C (pronobis@kth.se) Overview Overview Lecture 7: Introduction to C Wrap Up Basic Datatypes and printf Branching and Loops in C Constant values Wrap Up Lecture 7: Introduction

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Structure: - header files - global / local variables - main() - macro Basic Units: - basic data types - arithmetic / logical / bit operators

More information

Lecture 13 Hash Dictionaries

Lecture 13 Hash Dictionaries Lecture 13 Hash Dictionaries 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning, Rob Simmons, Iliano Cervesato In this lecture, we will discuss the data structure of hash tables further

More information

ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees. Introduction to Linked Lists

ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees. Introduction to Linked Lists ESc101: (Linear, Circular, Doubly) Linked Lists, Stacks, Queues, Trees Instructor: Krithika Venkataramani Semester 2, 2011-2012 1 Introduction to Linked Lists Each bead connected to the next through a

More information

CSE 303 Lecture 8. Intro to C programming

CSE 303 Lecture 8. Intro to C programming CSE 303 Lecture 8 Intro to C programming read C Reference Manual pp. Ch. 1, 2.2-2.4, 2.6, 3.1, 5.1, 7.1-7.2, 7.5.1-7.5.4, 7.6-7.9, Ch. 8; Programming in C Ch. 1-6 slides created by Marty Stepp http://www.cs.washington.edu/303/

More information

Contents. A Review of C language. Visual C Visual C++ 6.0

Contents. A Review of C language. Visual C Visual C++ 6.0 A Review of C language C++ Object Oriented Programming Pei-yih Ting NTOU CS Modified from www.cse.cuhk.edu.hk/~csc2520/tuto/csc2520_tuto01.ppt 1 2 3 4 5 6 7 8 9 10 Double click 11 12 Compile a single source

More information