return by address

closed account (jGAShbRD)
why does for each (marked as //)in this code not work? i dont understand. is it because q is pointing to p which is data in heap so in main we cant access it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

int * array(int size){
  int *p=new int[size];
  for(int i=0;i<size;i++){
    p[i]=1;
    std::cout<<*p<<std::endl;
  }
  std::cout<<p<<std::endl;
  return p;
}

int main(){
  int size;
  std::cout<<"Enter size";
  std::cin>>size;
  int *q=array(size);
  std::cout<<q<<" "<<std::endl;
  //for(auto x:q)
    //std::cout<<x;
  for(int i=0;i<size;i++){
    std::cout<<q[i];
  }
}
Last edited on
The pointer q is merely the address of an int. Given q and no supplemental information, there is no way to determine whether q points to a single int or to the first element of an array, and even if we assume that it points the first element of an array, there is no way to learn the size of the array. (Again, without extra information: the compiler is not smart enough to realize that size is the array size.)

Try:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>

std::vector<int> array(int size) 
{
  return std::vector<int>(size, 1); 
}

int main() 
{
  for (auto i: array(10)) std::cout << i << ' '; 
}
closed account (jGAShbRD)
isnt q the address of p and p is the array?
Isn't q the address of p and p is the array?

No: p has the type int*, pointer-to-int. Pointers are not arrays.

p is the address of the first element of an unnamed array of int. q and p both point to the same thing (although not at the same time.)

Last edited on
There is some confusion in the syntax between pointers and arrays. I wrote some stuff on this sometime back: http://www.cplusplus.com/forum/general/70081/#msg373940
Topic archived. No new replies allowed.