Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scanf to fill out a multidimensional array (C language)

I was wondering how to properly use scanf to fill out a multidimensional array.

Here's my code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, const char * argv[]) {

int n; //number of rounds
int* sArray; //multidimensional array that holds the scores of both players
int i;

scanf("%d", &n);

sArray = (int*) calloc (n * 2, sizeof(int));


for(i=0; i<n; i++) {
    scanf("%d %d", &sArray[i][1], &sArray[i][2]); 

}

return 0;
}

It gives me an error, "Subscripted value is not an array, pointer, or vector." Any help would be much appreciated!

like image 311
YSA Avatar asked Feb 16 '26 12:02

YSA


2 Answers

A two dimentional array is defined as follows: int sArray[N][M], but since you wanted to work with the dynamic memory I offer you to take a look at a pointer to pointer at int:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    scanf("%d", &n);
    int **sArray;
    sArray = (int **)malloc(n * sizeof(int *));

    int i;
    for(i = 0; i < n; i++)
    {
        sArray[i] = (int *)malloc(2 * sizeof(int));
        scanf("%d %d", &sArray[i][1], &sArray[i][2]);
    } 
    return 0;
}

Don't forget to clean-up after you are done with the array.

As mentioned in the commentaries, You don't need to cast the result of malloc if you work with pure c. I did this because my c++ compiler refused to compile it without this cast.

You might need to check errors during a dynamic allocation of the array. Read more here

like image 52
neshkeev Avatar answered Feb 18 '26 00:02

neshkeev


There are already a lot of good answers here on how to define your dynamic 2D array. But this variant was not yet mentionned, so I put it for the records.

As the last dimension of your array is fixed, you could define your 2D array as follows:

int (*sArray)[2]; //multidimensional array that holds the scores of both players
...
sArray = (int(*)[2]) calloc (n, sizeof(int)*2);  // self explaining

In this way, all the elements will be stored contiguously (each n element of the allocated array, is 2 contiguous integers), without the need for an array to arrays.

The rest of your code remains identical. Except that you shoud address sArray[i][0] and ..[1] instead of [1] and [2] and free memory at the end. In C array indexing starts always from 0 and goes to size-1.

Of course, this approach is strictly limited to 2D arrays where the last dimension is fixed.

Live demo with addressing

like image 27
Christophe Avatar answered Feb 18 '26 01:02

Christophe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!