Thinking in C: Chapt 7 – Pointers 101

This was a very interesting chapter. I had forgotten some basic concepts related to pointers and it was nice to refresh them.

Pointers are used to support reference semantics in C. When we pass an array to a function in C, we are in reality passing a pointer to it. Arrays CANNOT be passed by value in C.

Pointers allow us to create dynamic objects whose size we do not know at compile time. Dynamic objects are created with malloc or calloc, and live on the heap. When an object is no longer needed, it’s memory must be returned to the heap by using ‘free’. Another function that C gives us is realloc() which updates the size of memory alloctaed using malloc. We might want to use the sizeof operator when allocating memory. To use these functions be sure to include <stdlib.h>

C has a NULL pointer which does not point to any valid memory location. Since it does not point to a valid memory location, it cannot be dereferenced. A NULL pointer is usually used for comparisons, with pointers returned from a method (where a NULL pointer denotes an error).

C supports two operators for working with pointers to structs. The . operator and the -> operator. When we use the -> operator, we do not need to dereference the pointer to struct.

An interesting note: Most operating systems will free memory used by a program when it exits, however it is usually a good idea to explicitly free memory because if our program takes huge amounts of memory then it might exhaust all the memory available on the system.

Did the assignment. Learned something interesting. If I have a structure Employee

struct Employee {

char name[16] ;

}

struct Employee emp = malloc(sizeof(struct Employee));

emp->name = someCharPointer; //does not compile

strcpy(emp->name, someCharPointer); //works just fine

Why does the first line not work? I think it is because name is initialized as an array of 16 chars, while someCharPointer is also a char pointer, but we do not know it’s size. I think the compiler senses that things could go wrong and disallows the assignment.

Research:

  • Does realloc work if the memory was allocated using calloc()?
Advertisements

One Response to Thinking in C: Chapt 7 – Pointers 101

  1. As I website proprietor I visualize the satisfy here is certain brilliant , notices for your chores. Talk about familly allowances here caf

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: