📜  C/C++中的数组和指针的比较与例子

📅  最后修改于: 2022-05-13 01:55:27.233000             🧑  作者: Mango

C/C++中的数组和指针的比较与例子

什么是数组?

数组是存储连续内存位置的相同类型的多个项目的集合。每个元素的位置可以通过在基值上加上一个偏移量来计算,即数组第一个元素的内存位置。

句法:

例子:

C++
#include 
using namespace std;
int main()
{
    int i, j;
  
    // Declaring array
    int a[5];
  
    // Insert elements in array
    for (i = 0; i < 5; i++) 
    {
        a[i] = i + 1;
    }
  
    // Print elements of array
    for (j = 0; j < 5; j++) 
    {
        cout << a[j] << " ";
    }
    return 0;
}


C++
// C++ program to implement array
#include 
using namespace std;
  
// Driver code
int main()
{
    int a = 20;
    int* ptr;
    ptr = &a;
    cout << a << " " << ptr << 
            " " << *ptr;
    return 0;
}


输出
1 2 3 4 5 

大批

什么是指针?

指针是地址的符号表示。它存储变量的地址或内存位置。指针使程序员能够创建和操作动态数据结构。

句法:

例子:

C++

// C++ program to implement array
#include 
using namespace std;
  
// Driver code
int main()
{
    int a = 20;
    int* ptr;
    ptr = &a;
    cout << a << " " << ptr << 
            " " << *ptr;
    return 0;
}
输出
20 0x7ffe2ae2d4ec 20

数组和指针的比较

指针可用于访问数组元素,使用指针算法访问整个数组,使访问速度更快。数组和指针之间还有一些其他差异,这些差异将在下表中讨论。

S No.ArrayPointer
1type var_name[size];type * var_name;
2Collection of elements of similar data type. Store the address of another variable.
3The array can be initialized at the time of definition.Pointers cannot be initialized at definition.
4An array can decide the number of elements it can store.The pointer can store the address of only one variable.
5Arrays are allocated at compile time.Pointers are allocated at run-time.
6Memory allocation is in sequence.Memory allocation is random.
7Arrays are static in nature i.e. they cannot be resized according to the user requirements.Pointers are dynamic in nature i.e. memory allocated can be resized later.
8An array of pointers can be generated.A pointer to an array can be generated.
9Java Support the concept of an array.Java Does not support pointers.
10An array is a group of elements.Python is not a group of elements.