【问题标题】:How Pointer Array is used to store values of array?指针数组如何用于存储数组的值?
【发布时间】:2021-06-16 19:36:34
【问题描述】:

以下代码是我对这个挑战找到的答案

https://www.hackerrank.com/challenges/vector-sort/problem?isFullScreen=true&h_r=next-challenge&h_v=zen

int main() {
      
    int x,y,s=0;
    cin>>x>>y;
    int *arr[x];
    while(x--)
    {
        int num;
        cin>>num;
        arr[s]=new int[num];
        for(int i = 0; i<num ; i++)
        {
            cin>>arr[s][i];
        }
        s++;
    }
    while(y--)
    {
        int a,b;
        cin>>a>>b;
        cout<<arr[a][b];
        cout<<"\n";
    }
    
     return 0;
}

我的问题是指针数组“arr”如何存储第 13 行中的数组元素的值并打印第 21 行中的数组元素。

要使用存储在数组中的值,我们必须使用星号,对吗? 那么如何在没有星号作为前缀的情况下扫描和打印指针数组中的元素呢?

【问题讨论】:

标签: c++ arrays pointers dynamic-memory-allocation


【解决方案1】:
#include<iostream>
#include<conio.h>
using namespace std;
int main() {
      
    int size  ;
    cin>>size;
    int *array=new int [size];
 
 
 
 for(int i=0;i<size;i++){
    
 cout<< array[size]<<endl; //it will print zero beccause by default all values set to zero
    
    
 }   
}
      
      

这样我们就可以使用指针了。声明指针数组

【讨论】:

    【解决方案2】:

    N3337 5.2.1 下标说:

    表达式E1[E2]*((E1)+(E2)) 相同(根据定义)

    因此,arr[s][i] 表示*(*(arr + s) + i),它可以做星号可以做的事情。

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2010-09-24
      • 2021-04-09
      • 1970-01-01
      相关资源
      最近更新 更多