c++ - How to allocate memory dynamically using pointers? -
i have following task: creat program transform array array b in followin order: http://gyazo.com/29e434ebdc1e235fe0fc97c26ae9fe9c
the size of entered user, elements. print new elements of b. "use pointers"
examples: if input 1234567, program output 8888888.
here's code:
#include <iostream> using namespace std; int main() { int n; cout << "enter size of array" << endl; cin >> n; int a[n], b[n]; cout << "enter elements of array" << endl; for(int = 0; < n; i++){ cin >> a[i]; } for(int = 0; < n; i++){ b[i] = a[i] + a[n-i-1]; } for(int = 0; < n; i++){ cout << b[i] << " "; } return 0; }
there 1 problem have, says "use pointers" don't know shall use them , must used... in advance.
int a[n], b[n];
this code non-standard (when n
variable). compiler allows that, if try compile code in other one, won't work.
using pointers in case means, should allocate memory arrays dynamically, eg.
int * a, * b; = new int[n]; b = new int[n];
this code valid in terms of c++ standard.
remember though, have free allocated memory manually after don't need anymore:
delete[] a; delete[] b;
this should work rest of code left unchanged, since []
operator works pointers well.
and finally, if writing c++ program, surely should using std::vector
instead of c-style arrays...
edit: (in response comment)
if declare variable in following way:
int * a;
and write:
cin >> *(a + i);
it means:
- read data user , parse it;
- go
i
"steps" starting address (it "walks"i * sizeof(*a)
bytes a). - put data read user memory pointed place evaluated in step 2.
but when declare:
int (*a)[n];
the becames pointer array of n elements. since array convertible pointer first element, may think of previous line (for sake of explanation) as
int ** a;
in such case compiler tries same described earlier. walks i
pointers starting a, not *int*s. dereferences pointer getting int *
, attempts put there data written user. >>
operator of cin
not able translate text pointer , that's why compiler complains.
foot note
while you're learning using pointers, may think of <something> variable[]
being equal <something> * variable
pointing first element of array. lie (because array not a pointer, it's convertible pointer first element), helps understanding arrays have in common pointers. that's why can think of
int (* a)[];
as a
int ** a;
Comments
Post a Comment