Mario Plantosar
Mario Plantosar

Reputation: 804

Why does c print a different array the second time it's printed?

My cousin has a school project and we can't figure out why is the array different the second time it's printed when there is no values changing in between?

Basically you enter a number which states how many rows/columns will the matrix have, and during first loop he assigns a number to every position and prints out the random number. However, the second time we go through the matrix the numbers are different and it seems that they are copied through the matrix from bottom left corner to top right corner for some reason. It seems strange to us because we never assign a different value to a position in the array after defining it for the first time.

int i,j,n,matrica[i][j],suma=0;
srand(time(NULL));
printf("\nunesi prirodan broj N[3,20] = \n");
scanf("%d",&n);

for(i=0;i<n;i++) {
    for(j=0;j<n;j++) {
        matrica[i][j]=rand()%100;
        printf("%d, %d = %4d   ",i, j, matrica[i][j]);

        if(j==n-1) {
            printf("\n");
        }
    }
}

printf("\n");

for(i=0;i<n;i++) {
    for(j=0;j<n;j++) {
        printf("%d, %d = %4d   ", i, j, matrica[i][j]);

        if(j==n-1) {
            printf("\n");
        }
    }
}

And here is the result of this (the code I pasted here has 2 prints, and in the image there is 3 but every time you go through the matrix after the first time it's going to be the same):

enter image description here

Upvotes: 0

Views: 354

Answers (2)

autistic
autistic

Reputation: 15642

int i,j,n,matrica[i][j]

At this point I must ask, what value do you think i and j will have? Right there you're invoking undefined behaviour by referring to variables declared with automatic storage duration which you've not initialised. Anything after this point is... undefined behaviour.

Having said that, I noticed a few other parts that look strange. Which book are you reading? The reason I ask is that the people I know to be reading reputable textbooks don't have these problems, thus your textbook (or resource, whatever) mustn't be working for you...

I can't read the commentary inside of the string literals, which is a shame, since that's usually quite valuable contextual information to have in a question. Nonetheless, moving on, if this were me, I'd probably declare a pointer to an array n of int, after asking for n, like so:

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

int main(void) {
    size_t n;
    printf("Enter n, please: ");
    fflush(stdout);
    if (scanf("%zu", &n) != 1 || n == 0 || SIZE_MAX / n < n) {
        puts("Invalid input or arithmetic overflow...");
        return -1;
    }

    int (*array)[n] = malloc(n * sizeof *array);
    if (!array) {
        puts("Allocation error...");
        return -1;
    }

    /* now you can use array[0..(n-1)][0..(n-1)] as you might expect */

    free(array);
}

This should work for quite high numbers, much higher than int array[n][n]; would in its place... and it gives you that option to tell the user it was an "Allocation error...", rather than just SIGSEGV, SIGILL, SIGBUS or something...

... but nothing would be more optimal than just saving the seed you use to generate the random numbers, and the user input; that's only two integers, no need for dynamic allocation. There's no point storing what rand generates, amd you realise this, right? rand can generate that output purely using register storage, the fastest memory commonly available in our processors. You won't beat it with arrays, not meaningfully, and not... just not.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 59997

We need to use malloc to allocate the dynamic amount of memory.

After

 scanf("%d",&n) // PS You should check the return value - read the manual page

Put

 matrica = malloc(sizeof(int) * n * n);

And declare it as

int *matrica;

Then replace

matrica[i][j]

with

matrica[i * n + j]

And after you have finished with matrica - use free i.e.

free(matrica);

Upvotes: 3

Related Questions