Memory

Get an intuitive understanding of memory types and organization.

Introduction

At one point or another, we came across variables. They’re our go-to tool for:

  • Storing and processing information
  • Doing calculations and producing an output

To illustrate this, consider a scenario where we want to read the first name, age, and email address of a user, each separated with a space in a single line. Our code will display the entered data and store it in a file (user_data.txt) for later use.

Don’t worry if you’re not familiar with working with files in C! It is just an example for us to analyze.

Press + to interact
#include <stdio.h>
int main()
{
char inputBuffer[72];
char name[32];
int age;
char emailAddress[32];
fgets(inputBuffer, 72, stdin);
sscanf(inputBuffer, "%s %d %s", name, &age, emailAddress);
printf("Received from user: [%s] [%d] [%s]\n", name, age, emailAddress);
FILE *filePtr = fopen("output/user_data.txt", "a");
if (filePtr != NULL)
{
fprintf(filePtr, "%s %d %s\n", name, age, emailAddress);
fclose(filePtr);
printf("Saved user data to file!\n");
}
else
{
printf("Could not open file!\n");
}
return 0;
}

Enter the input below

Let’s give it a try! Type something like Mark 22 mark123@gmail.com (without the quotes). After running the code, we’ll be able to download the generated file and see the output.

Asking questions

Now, let’s ask a few questions about this simple code:

1.

We used variables like name, age, and emailAddress(lines 6, 7, and 8 highlighted in the code above) to store data in the program. Where are the variables stored?

Show Answer
Q1 / Q2

The answer to both the questions is inside the memory!

Remember when we were in school trying to learn a new subject. We were reading our notes or textbook and attempting to memorize them. Our brain stores the information somewhere for later use.

A computer does the same thing. It takes the information we give and uses ...