1

I am trying to cout an array in my C++ code:

#include <iostream>
using namespace std;

void fun(int *a) {
    a[3] = 1;
    for (int i = 0; i<sizeof(a)/sizeof(a[0]); ++i) {
        cout << a[i] << endl;
    }

}

int main(int *arry) {

    fun(arry);
    system("pause");
}

I got error Exception thrown: write access violation. **a** was 0x1. occurred at Line 5 by using VS2017.

But if I write "something normally" like below, it is no problem:

void fun() {
    int a[3] = { 1 };
    for (int i = 0; i<sizeof(a)/sizeof(a[0]); ++i) {
        cout << a[i] << endl;
    }
}

I think both snippets are doing the similar thing, but why the 1st isn't correct? I am confused now, I appreciate anyone can offer some suggestion? Thanks in advance!

leon365
  • 127
  • 2
  • 8
  • `int main(int *arry)` is not a standard declaration. Also you never check (or even know) the size of `arry`, so you have no guarantee that you can access its fourth element – UnholySheep Dec 07 '17 at 15:18
  • Also `sizeof(a)/sizeof(a[0]` does not work the way you think it does in the failing example, as `a` is a pointer, not an array – UnholySheep Dec 07 '17 at 15:20
  • Possible duplicate of [Access violation writing location 0xcccccccc](https://stackoverflow.com/questions/6085827/access-violation-writing-location-0xcccccccc) – Tom Dec 07 '17 at 15:22

0 Answers0