0

Considering I have the following array:

int * a = new int[1000]; 

I would like to pass this array to a function by reference. If I would be calling this function from main:

int main() { int * a = new int[1000]; func(a); //print the elements of the array for(int i=1;i<=sizeof(a);i++) cout<<a[i]<<" "; return 0; } 

My function would be:

void func( ??? ) { //write some elements in the array for(int i=1;i<=sizeof(a);i++) a[i]=i; } 

How do I have to declare func?

3

3 Answers 3

3

Well the primary flaw is that sizeof(a) doesn't do what you think it does, if int * a; is passed to your function. It just calculates the size of the pointer variable itself at compile time. There's no information kept with the pointer that it was allocated using new int[1000]; and the size was 1000.

You need to pass the array size explicitly with an additional parameter, or better use std::vector<int> a(1000); at all.

Sign up to request clarification or add additional context in comments.

Comments

1

You cannot just pass a, It should be,

func(a,1000); 

Your function will be,

void func( ??? ) --> `void func( int *a, size_t size)

1 Comment

This is wrong. a is a pointer, so sizeof(a) will (probably) be 8 bytes.
1

The idea is to accept an array of integers of a certain size.

void func(int (&arr)[1000]) { // insert logic here } 

The above will only accept int arrays of size 1000 - no more, no less.

You are not passing an array, though. You're passing a pointer, so you need to pass the size:

void func(int *arr, size_t n) { // insert logic here } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.