What's new

Closed Help: Input data in array using pointer c++

Status
Not open for further replies.

IIZeroHourII

Eternal Poster
Joined
Mar 16, 2016
Posts
866
Reaction
315
Points
348
Pa help po mga master jan assignment lang , wala ko mahanap sa google ehh

Sample Code ko po.
#include <iostream>

using namespace std;

int main()
{
int myarray[10],*p;

for(int x=0;x<10;x++)
{
cout<<"Enter a Number"<<endl;
cin>>*p;
myarray[x]=p;
}
}
 
So nag-declare ka ng int array (myarray) at pointer to int (*p). First issue, your pointer *p points to some random address and not to the address of myarray. That in itself is dangerous.

Tingnan mo ito, gagayahin ko yung code mo. Disregard mo muna yung input. Let's check the addresses first kung match yung addresses ng myarray at pointer.
Code:
#include <iostream>
#define SIZE 10

int main(void) {
    int myarray[SIZE], *p;
    int *homers_ptr = myarray;
  
    std::cout << "Address of 'myarray': \t\t" << static_cast<void *>(myarray) << std::endl;
    std::cout << "Address of 'p' pointer: \t" << static_cast<void *>(p) << std::endl;
    std::cout << "Address of 'homers_ptr': \t" << static_cast<void *>(homers_ptr) << std::endl;

    return 0;
}

And upon compiling, this is the result: (the addresses are going to be different on your machine). As per result below, hindi match yung pointer at address ng myarray pero match yung pointer ko (homers_ptr).
Code:
user@debian10:~/programming/cpp$ c++ ptr.cpp && ./a.out
Address of 'myarray':           0x7ffc246b9810
Address of 'p' pointer:         0x7ffc246b9930
Address of 'homers_ptr':        0x7ffc246b9810

Once na na-reconcile mo na iyan, saka ka palang pwedeng mag-proceed sa element assignment.

By the way, maski yung element assignment mo sa for loop, mali din.
 
Status
Not open for further replies.

Similar threads

Back
Top