Home > OS >  is this allowed in C pointers?
is this allowed in C pointers?

Time:12-24

i am learning c and i find this bit confusing about the pointers . is it allowed or is it possible to modify the variable int a using pointer variable ?

here's the code :

#include <iostream>
int main(){
    int a ; // int variable 
    int *p ; // pointer 


    a = 10 ;
    *p =15 ; 

    std:: cout << a ;
    return 0; 
};

does *p = 15 change the value of a ?
i got error when i tried to run the code :

zsh: bus error 

CodePudding user response:

There's no relationship between p and a. p points to invalid memory, and dereferencing or assigning to it is undefined behavior.

If you want modifications to p to affect a, you need to set where it points to.

int a;
int *p = &a;

CodePudding user response:

Silvio's answer is correct. Bus errors occur when your processor cannot even attempt the memory access requested. This usually happens when using a processor instruction with an address that does not satisfy its alignment requirements.

you can read more about this here.

  • Related