Here is a code snippet I was working with:
int *a;
int p = 10;
*(a+0) = 10;
*(a+1) = 11;
printf("%d\n", a[0]);
printf("%d\n", a[1]);
Now, I expect it to print
10
11
However, a window appears that says program.exe has stopped working.
The if I comment out the second line of code int p = 10; and then tun the code again it works.
Why is this happening? (What I wanted to do was create an array of dynamic size.)
There are probably at least 50 duplicates of this, but finding them may be non-trivial.
Anyway, you’re defining a pointer, but no memory for it to point at. You’re writing to whatever random address the pointer happened to contain at startup, producing undefined behavior.
Also, your code won’t compile, becauseint *a, int p = 10;isn’t syntactically correct — the comma needs to become a semicolon (or you can get rid of the secondint, but I wouldn’t really recommend that).In C, you probably want to use an array instead of a pointer, unless you need to allocate the space dynamically (oops, rereading, you apparently do want to — so you need to use
mallocto allocate the space, likea = malloc(2);— but you also want to check the return value to before you use it — at least in theory,malloccan return a null pointer). In C++, you probably want to use astd::vectorinstead of an array or pointer (it’ll manage dynamic allocation for you).