Thursday, December 20, 2012

Arrays and Points and then more Arrays and Pointers

This is the first lesson where without a video to watch and listen to.  Judging by the way I efficiently digest information.... this lesson wasn't completely ideal for me.  So, I took A LOT of notes. #handcramp  Anyways, while taking notes about the information I was reading and "NOT" just copying the lesson word for word.  I feel I actually was able to absorb the information and I almost fear it was more efficient than the videos.  So, here were tonight's Units

Lesson 16
16.1 Using Pointers with Offsets  
16.2 Intro to Array Indexing and Pointer Offsets: Part I
16.3 Intro to Array Indexing and Pointer Offsets: Part II
16.4 Intro to Array Indexing and Pointer Offsets: Part III
16.5 Intro to Array Indexing and Pointer Offsets: Part IV

I know it seems a little redundant to keep typing out those lessons but I haven't figured out how to write a loop code in this blog.  :-)

The basics of the lesson was to properly understand array indexing by multiplying the size of the element number and then add another offset to this in order to get the actual element.

The Goal: Create an array of four strings of text, each string a maximum of 6 characters long.  Then create a printf() statement that will print each of the four strings just as if they had been arrays.

 #include <stdio.h>

    int main() {

        char storage[]   = "12345678901234567890123";

        char *ptr = &storage[0];

        *(ptr + (6*0) + 0) = 'O';
        *(ptr + (6*0) + 1) = 'n';
        *(ptr + (6*0) + 2) = 'e';
        *(ptr + (6*0) + 3) = ' ';

        *(ptr + (6*1) + 0) = 'T';
        *(ptr + (6*1) + 1) = 'w';
        *(ptr + (6*1) + 2) = 'o';
        *(ptr + (6*1) + 3) = ' ';

        *(ptr + (6*2) + 0) = 'T';
        *(ptr + (6*2) + 1) = 'h';
        *(ptr + (6*2) + 2) = 'r';
        *(ptr + (6*2) + 3) = 'e';
        *(ptr + (6*2) + 4) = 'e';
        *(ptr + (6*2) + 5) = ' ';

        *(ptr + (6*3) + 0) = 'F';
        *(ptr + (6*3) + 1) = 'o';
        *(ptr + (6*3) + 2) = 'u';
        *(ptr + (6*3) + 3) = 'r';
        *(ptr + (6*3) + 4) = ' ';

        printf("The 1st string is: %s \n", (ptr + (6*0) + 0) );
        printf("The 2nd string is: %s \n", (ptr + (6*1) + 0) );
        printf("The 3rd string is: %s \n", (ptr + (6*2) + 0) );
        printf("The 4th string is: %s \n", (ptr + (6*3) + 0) );

        return 0;
    }

Output: The 1st string is: One
        The 2nd string is: Two
        The 3rd string is: Three
        The 4th string is: Four


No comments:

Post a Comment