Hi,
Why I get access violation in this code ?

char *arr[ 5 ];
for( int i = 0; i < 5; i++ )
    cin >> arr[ i ];

but not in this :

char *arr[ 5 ];
char list[ 5 ][ 30 ];
for( int i = 0; i < 5; i++ )
{
    cin >> list[ i ];
    arr[ i ] = list[ i ];
}

if arr is not accessible, so why in the second code I can access it ?

Recommended Answers

All 2 Replies

Because arr just an array of 5 pointers to char . When you have

char *list[5][30]

this makes 5 arrays of 30 char . So doing list[i] returns a pointer to one of the 5 arrays of 30 char , which is OK, because arr contains pointers to char .

If you want to assign actual values to arr , you would have to use new, like this:

char *arr = new char[5];

EDIT: Actually, I'm not sure that's right. You should also have a problem doing std::cin >> list[i] , since in both cases you're trying to insert something from stdin into a pointer to a char . Either way, I'm not sure that you ever be extracting from stdin to a pointer like that...

EDIT_2: I think that >> is overloaded in a different way for arrays of type char than for other types, probably so that you can read in a C-style string from stdin in a simple way. If you change your code to:

int list[ 5 ][ 30 ];
for( int i = 0; i < 5; i++ )
{
    cin >> list[ i ];
}

It should fail to compile.

Why I get access violation in this code ?

Because pointers are not magic. When you declare a pointer, it doesn't automatically point to an infinite amount of memory. In fact, it doesn't point to usable memory at all. You have to explicitly point it to memory that you own, either by assigning the address of an existing object:

char a[50];
char *p = a;

Or by requesting a block of anonymous memory from the heap:

char *p = new char[50];
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.