APS105 Textbook 12.2 - Pointers to Data Structures

Syntax

To create a pointer to a struct instance, use the following syntax:
struct *structPtr = &structName

To access the attributes set to the original struct through the pointer, you can dereference the pointer in () and then use the dot notation from 12.1:
(*structPtr).attributeName

Alternatively, you can use arrow notation, which abides by the following notation:
structPtr->attributeName
Both of these are the same thing.

For example:

// Note that this works when I run locally but not when I run in Obsidian... weird.

#include <stdio.h>
typedef struct PC {
	char CPU[9]; // assuming it follows R- ----x format, e.g. R9 5900x
	int memory; // in GB
	double GPU; // e.g. 3090, 3060
} PC;

int main(void) {
	PC matthewPC = {"R9 5900x\0", 64, 3060.5};
	PC *ptrToMatthewPC = &matthewPC;
	printf("CPU: %s\n", (*ptrToMatthewPC).CPU); // using dot notation
	printf("Memory: %d GB\n", ptrToMatthewPC->memory); // using arrow notation
	return 0;
}


Dynamic Memory Allocation of Data Structures

You can use malloc to allocate memory on the heap to a pointer to a struct.

Example:

#include <stdio.h>
#include <stdlib.h>
typedef struct Neuron {
  int neuronNum;
  double input;
} Neuron;

int main(void) {
  Neuron *pNeuron; // declaring a neuron pointer, pointing to junk memory
 
  pNeuron = (Neuron *)malloc(sizeof(Neuron));
  // allocating memory for neuron pointer and setting neuron pointer to the address
  // where the memory is allocated
  
  pNeuron->input = 23.96;
  printf("pNeuron->input = %.2lf\n", pNeuron->input);
  free(pNeuron);
  return 0;
}