I'm trying to findout the size of the array. But instead of giving it 5 it is giving 2. Which is not correct. Formula for finding the size of the array is this. int size = sizeof(pArr)/sizeof(int); You can see the working code here. For your copy code is shown below.

#include <iostream>

void printArray(int* pArr){
    //find size of the array. It should be 5 but 
    //below it is calculating it 2. Why?
    int size = sizeof(pArr)/sizeof(int);
    std::cout << "sizeof pArr: " << size << "\n";
    for(int i=0; i<size; i++){
        std::cout << *(pArr+i);
    }
}

int main(){
    int another[] = {1,2,3,4,5};    
    printArray(another);
    for(int j=0; j<5; j++){
    // std::cout << arr[j]<< "\n ";   
    }//end for

}//end main

This post may give you a hint?

For your code to work safely without passing a size parameter, you would have to change it to something like this...

#include <iostream>

void printArray(int* pArr){
    //find size of the array. It should be 5 but 
    //below it is calculating it 2. Why?
    //int size = sizeof(pArr)/sizeof(int);
    //std::cout << "sizeof pArr: " << size << "\n";
    for(int i=1; i<=pArr[0]; i++){
        std::cout << *(pArr+i);
    }
}

int main(){
    int another[] = {5,1,2,3,4,5};    
    printArray(another);
    for(int j=0; j<another[0]; j++){
    // std::cout << arr[j]<< "\n ";   
    }//end for

}//end main
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.