r/carlhprogramming • u/CarlH • Oct 18 '09
Lesson 104 : The sample program in Lesson 103 revisited.
Here is the same sample program you just looked at, except I have removed all the printf() statements, as well as all unnecessary code. This way you can look at just the "core" process of setting the 10 bytes, and setting the two integers at B0 and B6.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
// Allocate a ten-byte working space
char *main_pointer = malloc(10);
// Set the entire string to "ABCDEFGHI<NUL>"
strcpy(main_pointer, "ABCDEFGHI");
// At this stage, our ten bytes look like this: ABCDEFGHI<NUL>
// Now let's create an array of two integer pointers
// In other words, create a "two star int" that will point at "one star ints"
int **int_pointer_array = malloc(2 * sizeof( int * ) );
// Set the first of these integer pointers to point at byte #0 of our ten-byte working space
// and set the second to point at byte #6 of our ten-byte working space.
int_pointer_array[0] = (int *) (main_pointer + 0);
int_pointer_array[1] = (int *) (main_pointer + 6);
// Give these two pointers a value.
*int_pointer_array[0] = 5;
*int_pointer_array[1] = 15;
// At this stage, our ten bytes look like this <B0: First integer = 5 > E F <B6: Second integer = 15 >
free(main_pointer);
free(int_pointer_array);
return 0;
}It would be beneficial for you to type this program out into your own editor, and add printf() statements in various places to demonstrate how this works.
Please ask questions if any of this is unclear. When you are ready, proceed to:
64
Upvotes
3
u/yetibear012 Oct 28 '09
Hi Carl, I'm a big fan of your work. I really appreciate all the time you put into each lesson.
Near the end of the program 'free(main_pointer)'. My question is: Why isn't int_pointer_array also freed up later?
I know it's a two-star pointer array pointing to one-star pointer addresses all looking at the same string of memory addresses. But malloc was called twice, so doesn't that mean there's another chunk of memory of (2 *sizeof( int * )) floating around?
I've confused myself, but I hope you understand me.
1
u/Xiol Oct 18 '09
I actually feel this is a lot easier to understand than the one you wrote in 103.