If you are reading this you want to know more about c pointers. That’s a good thing. Even if you don’t program in C very often, understanding pointers gives you a deeper understanding how programming and memory works “under the hood”. Learning pointers will make you a better programmer. Read more →
Tag: c pointers
Pass by Value
In the strictest sense of the word, everything in C is pass-by-value. This often confuses beginning C programmers, especially when it comes to pointers, arrays, and structs. So what do we mean when we say pass-by-value and pass-by-reference.
When we pass-by-value we are passing a copy of the variable to a function. When we pass-by-reference we are passing an alias of the variable to a function. C can pass a pointer into a function but that is still pass-by-value. It is copying the value of the pointer, the address, into the function. In C++ a reference is an alias for another variable. C doesn’t have this concept. Read more →
Discussions of pointers and arrays in C seem to be a holy war. On one side you have the people who say pointers are not arrays and that everybody must know that. On the other you have the people who say arrays are treated as pointers and so there shouldn’t be a distinction, it just confuses people. Turns out both sides are right. Read more →
When C was created, in 1972, computers were much slower. Most programs were written in assembly. C came along as a better assembly allowing programmers to manipulate memory directly with pointers. Programmers worked much closer to the machine and had to understand how memory worked to make their programs efficient. Read more →
When first learning C pointers there is one thing I wish had been better explained; operator precedence vs order of operations.
1 2 3 4 5 6 |
int myarray[4]= {1,2,3,0}; int *p = myarray; int out = 0; while (out = *p++) { printf("%d ", out); } |
The above example prints out 1 2 3. Code like *p++ is a common sight in C so it is important to know what it does. The int pointer p starts out pointing to the first address of myarray, &myarray[0]. On each pass through the loop the p pointer address is incremented, moves up one index in the array, but the previous p unincremented address (index) is dereferenced and assigned to the out variable. This happens until it hits the fourth element in the array, 0 at which point the while loop stops. But what does *p++ do? And how does it move from one element in the array to the next. Read more →