Arrays and pointers
Arrays and pointers
An array is a variable that can store multiple values. For example, if you want
to store 100 integers, you can create an array for it
int data[100];
dataType arrayName[arraySize];
For example,
float mark[5];
Here, we haven't specified the size. However, the compiler knows its size is 5
as we are initializing it with 5 elements.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
This program declares an integer array numbers of size 5. It then uses a loop to input five
numbers from the user and stores them in the array. Finally, it displays the entered numbers
using another loop.
#include <stdio.h>
int main() {
// Declare an array to store numbers
int numbers[5];
return 0;
}
Pointers
Address in C
If you have a variable var in your program, &var will give you its address in the
memory.
We have used address numerous times while using the scanf() function.
scanf("%d", &var);
Here, the value entered by the user is stored in the address of var variable.
Let's take a working example.
#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);
Output
var: 5
address of var: 2686778
C Pointers
Pointers (pointer variables) are special variables that are used to store
addresses rather than values.
Pointer Syntax
int* p;
int *p1;
int * p2;
Example: C program that uses pointers to swap the values of two variables:
#include <stdio.h>
int main() {
int num1, num2;
return 0;
}