Initialize pointer to an int[]

1.) How to declare and initialize the pointer to an array of integers ?
There is error in 2nd line after main() : scalar obj array requires one element in initializer .

Below is my attempt :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
using namespace std ;

int main () {
 char *str = "Raman" ;
 int (*arr)[5] = {1,2,3,4,5};
 for (int i=0 ; i<5 ; i++) {
    cout <<"\n"<< *(str+i)<<"\t"<<((void*)str+i) ;
 }

 for (int i=0 ; i<5 ; i++) {
    cout <<"\n"<< *(arr+i)<<"\t"<<(arr+i);
 }
 return 0 ;
}


It might be done like below :
1
2
int a[] = {1,2,3,4,5};
int (*arr)[] = &a ;

I want to do it in one line .
Last edited on
er... why?

The short answer is it can't be done. In order for your pointer to point to anything you have to have an array for it to point to. You can't make it point to a temporary array. It'd be like trying to do something like this:

int* ptr = &5;

The only time that's allowed is with c-strings.
OK!!
well I just wondered if there was a different syntax to it .
Here's my changed program!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
using namespace std ;

int main () {
 char *str = "Raman" ; 
 int a = {1,2,3,4,5};
 int (*arr)[5] = &a;
 for (int i=0 ; i<5 ; i++) {
    cout <<"\n"<< *(str+i)<<"\t"<<((void*)str+i) ;
 }

 for (int i=0 ; i<5 ; i++) {
       cout <<"\n"<< *(*arr + i) <<"\t"<<(arr+i);
 }
 return 0 ;
}


If any improvements , please suggest ..btw thanks
Yes, this line int (*arr)[] = &a ; makes no sense.

You could do this:

1
2
int A[] = {1,2,3,4,5};
int *pA = A;


now pA has the address of the array A and u can do all that pointer arithmetic.
1
2
cout << "address is: " << pA; //will show the address of pA
cout << "i = " << pA[i];  //for i=0 to 4 will show the elements of pA 


output:
address is: //some address of pA
i = 1, 2, 3, 4, 5



Note that cout << A; will also give you the address of the array A just like pA did.
Last edited on
thanks for pointing it out soranz.
I did it the harder way.
does this help... the name of the array is a pointer to the first thing in your array, so..
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

int main(){
   int array[3] = { 2 , 3 , 4 };
   *array += 3;
   std::cout<<*array<<std::endl;
   
   *(array + 2) += 3;
   std::cout<<(*array+2)<<std::endl;

   return 0;
}


outputs 5 and 7..
Topic archived. No new replies allowed.