-3

This is a function to fill the array with random numbers. n is the user input,p[n][n] is the array I try to create.I wanna use 2 functions named fillPin2d and showPin2d in order one function to fill the array with random numbers and one to print the array.The program keeps asking to enter an integer and its doesn't show the array I created.

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

void fillPin2d(int n,int p[n][n])
{
    int i,j;
    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
            p[i][j]=rand()% 11;

}
void showPin(int n,int p[n][n])
{
    int i,j;

    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            printf("%d\n",p[i][j]);
        }
    }
}

main() {
   int n;

   do {
        printf("Enter an integer n>5: \n");
        scanf("%d",&n);
    }while(n<=5);

    int p[n][n];
    fillPin2d(n,p);
    showPin(n,p);
    system("pause");
}
  • include the code in the question and format it properly. Don't post it in comments like that – phuclv Dec 25 '19 at 07:08
  • And please ask an actual question. What specific problem are you encountering? – kaylum Dec 25 '19 at 07:11
  • "doesnt run correctly". Can you please be more precise? Does it crash? Does it print nothing? Does it print some correct results and some wrong results? Also, please format the code so that it is readable. – kaylum Dec 25 '19 at 07:19
  • 1
    What is the input your are entering? `"Enter an integer n>5` implies you are entering a number greater than 5. But the condition `while(n>5)` would be wrong for that as it will keep looping unless the number is less than or equal to 5. – kaylum Dec 25 '19 at 07:27
  • BTW, it's `int main(void)`, not `main()`. What compiler are you using? – Bob__ Dec 25 '19 at 09:27
  • What is the range that you need? The formula you are using will produce numbers in [0, 10], but you may want to also use `srand` once in `main`. – Bob__ Dec 25 '19 at 09:34
  • I am using Dev C, the range i need is random numbers between 1-10 depending to the size of the array i give to the variable n which is the size of the array. – Black Mamba Dec 25 '19 at 15:09

1 Answers1

1

Your question is on the condition of "while". You want a n>5, so what you should put into "while" should be "n<=5", that way you can break the "while" if n is actually greater than 5.

A more thing to say, it's better to use malloc than just use int p[n][n]. Because when you use int p[n][n], the memory of p is allocated on the stack, which may make the stack overflow if the n is too large. And if you use malloc, the space is on the heap, and you can easily change the size of p by using realloc().

On many IDEs(for example,visual studio), the syntax of int p[n][n] is error, the IDE will tell you to give a constant instead of a variable.

I think you can view more discussion on:

  1. Creating Dynamic Array without malloc
  2. Dynamic arrays in C without malloc?
Sinon
  • 131
  • 4