Home > OS >  Declaring a random pointer and storing numbers on the next 5 addresses, but its not outputting the n
Declaring a random pointer and storing numbers on the next 5 addresses, but its not outputting the n

Time:12-10

I wanted to see if it was possible to store numbers on the addresses that come after variable a's address.

 //declariing a  variable
int a=0;
// declaring a pointer
int *str;
//assigning 'a' adress to the pointer
str =&a;

//storing numbers on next 5 adrdess starting from 'a' adress
for(int i =0; i<5;i  ){
   cout<<"input number %i: ";
cin>>*(str i);
}

//outputing numbers stored on next 5 addresses starting from 'a'

for(int j =0; j<5;j  )
cout<<"content: "<<*(str j);

but when i try to store numbers on the next 2 addresses it works fine:

  //declariing a  variable
int a=0;
// declaring a pointer
int *str;
//assigning 'a' adress to the pointer
str =&a;

//storing numbers on next 2 adrdess starting from 'a' adress
//for(int i =0; i<5;i  ){
   cout<<"input number %1: ";
   cin>>*(str 1);
   cout<<"input number %2: ";
cin>>*(str 2);
//}

 //outputing numbers stored on next 2 addresses starting from 'a'

//for(int j =0; j<5;j  )
cout<<"content1: "<<*(str 1);
cout<<"content2: "<<*(str 2);

CodePudding user response:

You are attempting to write to memory that you do not own.

Repeated from comment, if a was an array: int a[5] = {0};, then the expression str = &a[0]; would point to memory your process owns, allowing the follow-on code to populate the elements of the array via eg str[0], str[1]....

I am a new to C , so forgive the C approach, but see the following commented code describing the differences, i.e. to create array space, then use a pointer to point to the space...

int main(void)//minimum signature of main includes void
{
    int a[5] = {0};//array of 5 int
    // declaring a pointer
    int *str;//int pointer
    char in;
    char buf[20];
    //assigning 'a' address to the pointer
    str =&a[0];// point pointer to array

    //storing numbers on next 5 address starting from 'a' address
    for(int i =0; i<5;i  )
    {
        //cout<<"input number %i: ";//see comment below code
        cout<<"input number: ";
        cin >> in;
        a[i] = in - '0';//use char to convert input to digit value
    }

    //outputting numbers stored on next 5 addresses starting from 'a'

    for(int j =0; j<5;j  )
    {
        sprintf(buf, "content is: %d\n", a[j]);//using stdio.h
        cout <<  buf;
    }
    return 0;
}

An aside:
Some of your stdout streaming calls, eg.

cout<<"input number %i: "; 

appear to use format specifiers.

C streams don't use format-specifiers like C's printf()-type functions; they use manipulators. reference

  •  Tags:  
  • c
  • Related