简体   繁体   中英

Variable sized array

So, I am stuck in a coding problem on hakerrank. The problem is in the link https://www.hackerrank.com/challenges/variable-sized-arrays my code in c++ goes as follows,

#include<stdio.h>
#include<stdlib.h>
using namespace std;

main() {
  int n, q;
  scanf("%d %d", &n, &q);
  int **a = new int*[n];
  int k;
  for (int i = 0; i < n; i ++) {
    scanf("%d", &k);
    int *c = new int[k];
    for (int j = 0; j < k; j ++) {
      scanf("%d", &c[i]);
    }
    a[i] = c;
  }

  int s, f, *z;
  for (int i = 0; i < q; i ++) {
    scanf("%d %d", &s, &f);
    z = a[s];
    printf("%d\n", z[f]);
  }
}

Every time I run it,it shows garbage values.please help me out.

You are confusing indices. scanf("%d", &c[i]) should be scanf("%d", &c[j]) .

You have mixed a lot of C with C++. It looks like you are trying to implement a 2D array with variable 2nd dimension. try below program with little modification in your code:

#include<iostream>

using namespace std;
int main()
{
    int n, q;
    cout<<"Enter the rows : \n" ;
    cin>>n>>q;
    int **a = new int*[n];
    int k;
    for (int i = 0; i<n; i++)
    {
        cout<<"Enter the column : \n" ;
        cin>>k;
        int *c = new int[k];
        for (int j = 0; j<k; j++)
        {
            cout<<"Enter the value["<<j<<"] : \n";
            cin>>c[j];
        }

        a[i] = c;
    }
    int s, f, *z;
    for (int i = 0; i<q; i++)
    {
        cout<<"Enter the row and column to print : \n" ;
        cin>>s>>f;
        z = a[s];
        cout<<z[f]<<endl;
    }
    return 0;
}

Just FYI: You still need to add proper error handling scenarios.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM