Home  >  Article  >  Backend Development  >  The difference between pointers and arrays in C language

The difference between pointers and arrays in C language

WBOY
WBOYforward
2023-08-26 20:49:121087browse

The difference between pointers and arrays in C language

The details about pointers and arrays showing their differences are as follows.

Pointer

A pointer is a variable that stores the address of another variable. When memory is allocated to a variable, the pointer points to the memory address of the variable. The unary operator ( * ) is used to declare pointer variables.

The following is the syntax for pointer declaration.

datatype *variable_name;

Here, datatype is the data type of the variable, such as int, char, float, etc., and variable_name is the variable name given by the user.

The following is a program that demonstrates pointers.

Example

Online demonstration

#include <stdio.h>
int main () {
   int a = 8;
   int *ptr;
   ptr = &a;
   printf("Value of variable a: %d</p><p>", a);
   printf("Address of variable a: %d</p><p>", ptr);
   return 0;
}

The output of the above program is as follows.

Value of variable a: 8
Address of variable a: -2018153420

Array

An array is a collection of elements of the same type located in contiguous memory locations. The lowest address in the array corresponds to the first element, while the highest address corresponds to the last element. Array indexing starts at zero (0) and ends with the array size minus one (array size - 1).

Output

The following is the syntax of the array.

Output

The following is the syntax of the array. >

type array_name[array_size ];

Here, array_name is the name of the array, and array_size is the size of the array.

The program to demonstrate the array is as follows.

Example

Live demonstration

#include <stdio.h>
int main () {
   int a[5];
   int i,j;
   for (i = 0;i<5;i++) {
      a[i] = i+100;
   }
   for (j = 0;j<5;j++) {
      printf("Element[%d] = %d</p><p>", j, a[j] );
   }
   return 0;
}

Output

The output results of the above program are as follows.

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104

The above is the detailed content of The difference between pointers and arrays in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete