-4

Hi, I've got this function:

void vector(int imputC[]) { 
    //return v*   
    //imputC[].lenght
    int a =sizeof(imputC) / sizeof(int);
    // float v[2 * a + 2];
    // v[0]=0;
    for (int i = 0; i < a ; i++)
        v[i] =(float)imputC[i];

    for(int j = 0; j < 10; j++)
        cout << a << endl;
}

And main:

int main() {
    int array[] = { 23, 5, -10, 0, 0, 321, 1, 2, 99, 30 };
    // float *v[22];
    vector(array);
}

And size of a is 1. Why is that? I don't understand, I think that's is the only object.

İsmet Alkan
  • 5,361
  • 3
  • 41
  • 64
Luke Smith
  • 1
  • 1
  • 4
  • 3
    Is that the best formatting you could come up with? – Nawaz Jan 10 '13 at 17:22
  • Exactly why are you printing out `a` 10 times? – Marc B Jan 10 '13 at 17:23
  • [sizeof()](http://en.wikipedia.org/wiki/Sizeof) is not for that. *"sizeof is used to calculate the size of any datatype, measured in the number of **bytes required to represent the type**"*. Read the documentation before using a function. – m0skit0 Jan 10 '13 at 17:23
  • @MarcB - just to really really make sure that a is 1. That, or to make the array have 1111111111 elements. – slugonamission Jan 10 '13 at 17:24
  • Assuming you're actually using C++, just use a vector instead of an array, and copying becomes trivial (just use an assignment like `auto b = a;`). – Jerry Coffin Jan 10 '13 at 17:24

2 Answers2

3

The expression sizeof(imputc) doesn't work in your function, as the array is passed as a pointer and doesn't retain the size of the original array. So that expression returns only the size of the pointer not the array it points to.

If you must pass an array to a function that needs to know the number of items in the array, you must always pass the array size as an argument to that function.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

In a declaration of a function that takes an array type as an argument the array type decays into a pointer to the first element. So

void vector(int imput[])

is the same as

void vector(int *imput)

A function that takes an array argument needs to have some other way of getting the number of elements in the array.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165