-3

This program is crashing. Is there some limit in C using n length array? It works in C++ (using cin cout). Thanks for your time.

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

int main(int argc, char *argv[])
{
  int n;
  printf("n\n");
  scanf("%d\n",n);
  int arr[n];
  system("PAUSE");  
  return 0;
}
Casey
  • 41,449
  • 7
  • 95
  • 125
  • How big is the number you are passing in? – Mysticial Jun 20 '13 at 18:50
  • 1
    @Mysticial Big enough not to fit into the memory which is to be accessed by a wannabe pointer-to-`int` which is an uninitialized non-pointer instead... –  Jun 20 '13 at 18:51
  • @Mysticial (that was tough and confusing... he's writing `scanf("%d", n);`) –  Jun 20 '13 at 18:52
  • your scanf is wrong, it should be &n – pm100 Jun 20 '13 at 18:53
  • 2
    By the way, this shouldn't even compile in strict mode for C++. C++ doesn't have VLAs. –  Jun 20 '13 at 18:54
  • 2
    `"it works in C++"` is ***not*** a reason that it should work in C – Mike Jun 20 '13 at 18:55
  • Also, without knowing why it is crashing, it is difficult to help. What error messages did you recieve (if any)? Do you know how far your program gets before crashing? – wlyles Jun 20 '13 at 18:57
  • 1
    Learn how to use a debugger, so you can determine where it crashed. – Erik Olson Jun 20 '13 at 18:57
  • 1
    Please don't edit your code and insert the fix. It changes the nature of the problem. Instead go down to the answer that fixed your problem and click the check mark. Then people will know your problem is solved. – Mike Jun 20 '13 at 19:01

2 Answers2

6

Your code has another problem:

scanf("%d\n", n);
//           ^^
// should be &n

scanf expects a pointer, while you're passing int.

awesoon
  • 32,469
  • 11
  • 74
  • 99
1

As i pointed out in another answer of mine see here

that when using scanf() one should avoid using characters other than format specifiers like(%d or %s) because when you write any thing in scanf between the quotes it expects you to enter that part exactly as it is there, which is very problematic specially for newbies.

And the most important error in your answer is this:

scanf("%d",n)
           ^ 

You have to pass the address of the variable for which you want to take input so it should be &n.

Community
  • 1
  • 1
0decimal0
  • 3,884
  • 2
  • 24
  • 39