Tuesday, February 17, 2009

Linux Tips

- Changing Linux root password

- Ways of saying 'Hello! World' : http://www.fitzrovian.com/hello.html
- sizeof (type) requires parenthese, while sizeof expression
does not.

- How to easily read a declaration from left to right:
transform function argument types from inside out first
move the base type to the end
add outer parentheses if there's an initial *
change every (*...) to ... ->
one -> for each *
move qualifiers, so * const becomes const ->

Example: const int *(**const x [])()

*(**const x [])() const int base type to end
(*(**const x [])()) const int add outer parens
(**const x [])() -> const int remove outer ()
x [] const -> -> () -> const int remove inner ()

array of constant pointers to pointers to functions
returning pointers to constant ints

- p + 1 == &p [1]


Tuesday, February 10, 2009

Unfolding 2-D array in C

Last weekend my friends and I had a discussion on 2-D array in C. Surprisingly it went long as everyone had some points and knowledge to share :) Finally we could gather some important information and understood this pearl of C better.

I'll clear this idea with C code snippets.

// Declare an array
int arr[2][3]= {1,2,3,4,5,6};

It's size is 2*3*sizeof(int) = 24 bytes (Intel x86)

okay, now what will get printed for following statements:
// Say starting address is 1024

o) print &a + 1
o) print a + 1
o) print *a + 1

To answer these questions better, I'll explain what exactly is a 2-D array. When we declare and define a 2-D array, it's like a new user defined type to C. It's a pointer to a memory location that contiguously contains storage of 6 integers. Logically it's like holding many 1-D array in a followed by one-another.

Ans 1: When you say '&a' , it implies address of user defined type and it's 1024. Now incrementing it by 1 means moving the pointer by the size of this type which is 24 bytes. Thus it'll print 1048.

Ans 2: 'a' fetch us address of 1-D array or 0th row of our matrix. a+1 would get us address of next row i.e. 1024 + (3*4) = 1036

Ans 3: '*a' would get you the 0th element of 0th row which is 1. So *a + 1 would get us 2.