[C] Struggling with structs, and pointers.

Okay! So, both your questions deserve answers in their own right, but I'll do my best to sum them up here.

Pointers are very simple in concept, but difficult to understand for a beginner.

Most modern computers' memory is separated into chunks of 8 bits (or 1 byte) of storage. The computer references these chunks using addresses. When you create a pointer, you point to a particular address in memory.

These addresses are contiguous, so address 999 is physically right next to 998 and 1000. This allows you to do some crazy fast operations. For example, say you allocated a block of memory, the size of 3 32 bit integers, you can easily access any of these integers with a single pointer.

A simple implementation of this is as follows.

#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
int main(void)
{
int foo[] = { 1, 2, 3 };

int *i = &foo; //assign a POINTER to the ADDRESS of our array of integers. int *i means a pointer to an integer. 
    //The type of the pointer is important which I'll explain later. &foo means simply "the address of foo".

    //Here we have a simple for loop that iterates over the array
for (int j = 0; j < 3; j++)
{
    printf("Address of %i = %x\n", *i, i); //print out the address and integer stored there
    i++; //increment the pointer. Remember I said type was important? Well, i++ basically means jump the size of its type. 
//If we were using a char, it'd be 1 byte, but since we're using a 32 bit integer, it's 4 bytes, or 4 addresses. 
//if the pointer pointed to the address 0x000001, it would now point to the address 0x000005 after incrementing!
}
}

You can do a ton of really crazy stuff with pointers. This is a decent tutorial and should help get you started!

Structs are the forerunners to objects used in object-oriented programming, but are really cool in their own way. When you define a struct, you group a bunch of variables together (physically in memory AND programmatically) allowing you to use a single pointer to access any of the struct's variables.

This is a pretty good tutorial on structs.

Hope this helped, and if you have any further questions please feel free to ask.

/r/learnprogramming Thread