Home > Backend Development > C++ > body text

The difference between pointers and arrays in C language

WBOY
Release: 2023-08-26 20:49:12
forward
1086 people have browsed it

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;
Copy after login

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;
}
Copy after login

The output of the above program is as follows.

Value of variable a: 8
Address of variable a: -2018153420
Copy after login

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 ];
Copy after login

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;
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template