cody
cody

Reputation: 137

Pointer to char array

int main( ){    
    char a[2];
    char *p;
    p=&a[0];
    *(p+5)='g';
}

In the above program I defined a pointer pointing to char array but the array is 3 bytes only. Let me tell you more clearly,for instance let us assume the char array address is 1000 so it takes upto 1003 bytes, but using a pointer I am storing an ASCII value of 'g' at 1005 location. Is that okay with the compiler ? Is that memory an static alloacted one ? or Can be used again ? Will that value be permanently stored in it or no?

Upvotes: 0

Views: 2348

Answers (4)

naveen tilawalli
naveen tilawalli

Reputation: 11

first of all you have declared char array to hold only 2 chars and not 3. If you attempt this the behavior will be undefined.

Upvotes: 1

Donotalo
Donotalo

Reputation: 13035

char array address is 1000 so it takes upto 1003 bytes

Typically a char is 1 byte in length. So a char array having 2 chars will take two bytes: 1000 and 1001.

Is that okay with the compiler ?

It is fine with the compiler. C allows you to do whatever thing you want to do, including crashing the system.

Is that memory an static alloacted one ? or Can be used again ? Will that value be permanently stored in it or no?

That memory is not allocated to be used by your program. You promised that you'll be using only location 1000 and 1001. If you access anything beyond that, that is undefined behaviour. Anything can happen and nothing is guaranteed in such cases.

Upvotes: 3

Scott C Wilson
Scott C Wilson

Reputation: 20046

This is fine by the compiler, but might cause a problem at runtime, since who knows what's at the address you're writing to.

Upvotes: 2

GWW
GWW

Reputation: 44161

You are changing a random memory location in your program. This is undefined behavior and it could have random effects on your program such as a segmentation fault.

Upvotes: 4

Related Questions