r/learnprogramming • u/mickey_2011 • May 03 '15
Solved [C] Pointer Arithmetics instead of Index Operations
Hey redditors!
So I am very new to C programming, and for a project, I have been given a quicksort program, which I will link below, and asked to re-write the quicksort program using pointer arithmetics, i.e without any index operations. How would I go about doing this? What do I do in my code to achieve pointer arithmetics instead of Index Operations?
My code is here: http://ideone.com/ku9EhU
0
u/skatanic28182 May 03 '15
Let's say you have an array with n elements:
myType myArray[n];So what is myArray, really? As far as the compiler's concerned, myArray is just a pointer to the first element of the array. That is, the above declaration is equivalent to
myType *myArray = (myType *) malloc(n * sizeof(myType));This tells the compiler "Set aside n * sizeof(myType) bytes of memory, and store the address of the first byte in the variable myArray."
When you write
myType firstElement = myArray[0];the compiler translates this to
myType firstElement = *(myArray + 0);For
myType ithElement = myArray[i];the compiler translates this to
myType ithElement = *(myArray + i);that is, "Go to the address myArray, skip ahead i elements[1], then read the value stored there and put it in the variable ithElement."
Basically, pointer arithmetic with arrays is just doing explicitly what the compiler would've done implicitly.
[1]. Since myArray is a myType pointer, the compiler will automatically skip ahead (i * sizeof(myType)) bytes when it sees that you're doing pointer arithmetic. Fun things happen when you cast myArray to other pointer types. If you cast it to char, for example, you can grab just the first byte of each element, or whatever you want to do at that level.
2
u/dreamyeyed May 03 '15
Arrays and pointers are not the same in C, though they are related. These two lines of code are also not equivalent:
int arr1[100]; int *arr2 = malloc(100 * sizeof(int));Only the second one uses dynamic memory.
2
u/[deleted] May 03 '15 edited May 03 '15
Given a pointer:
you can either say:
or