Array size set by variable

Asked

Viewed 50 times

0

I checked and I see no mistakes.

void exibe (int * , int);

int main(){

  int n;
  int m[n], i;

  printf("Digite o numero de elementos do array : ");
  scanf("%d",&n);
 
  for (i = 0; i < n; i++){
    printf("Digite o %d numero : ",i + 1);
    scanf("%d",&m[i]);
   }

  exibe(m,n);

  system("pause");
  return 0;
}

void exibe (int *m, int n){
   int i;

   for (i = 0, i < n; i++)
    printf("Numero %d = %d \n",m[i]);
 }
  • What is the expected result? There is an error message or something like that?

  • Appears expected ; before ')' token

  • the command is wrong, must use ; on has a comma: for (i = 0; i < n; i++)

1 answer

1


There are typos like , in place of ;, missing put two data in a text template to print that expects two different data and the biggest problem is that is trying to create a array with a data that does not exist yet (even exists but is something caught almost randomly in memory), that usually happens with this wrong idea that people learn that they have to declare all variables before starting the code, which would prevent this code pattern.

#include <stdio.h>

void exibe (int *m, int n) {
    for (int i = 0; i < n; i++) printf("Numero %d = %d \n", i, m[i]);
}

int main() {
    int n;
    printf("Digite o numero de elementos do array : ");
    scanf("%d", &n);
    int m[n];
    for (int i = 0; i < n; i++) {
        printf("Digite o %d numero : ", i + 1);
        scanf("%d", &m[i]);
    }
    exibe(m, n);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

This has there its risk but nothing critical for an exercise, if someone put a very large number, bigger than the capacity of the stack gives error, then the number should be validated before.

  • Manage to figure out the parts I missed, now the code is working. Thank you so much for the help!!

  • @Matheussantos you know you can vote for everything on the site too?

  • Yes, I’ll vote for other posts too.

  • @Matheussantos you can vote on this to start. Voting is different from acceptance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.