Reputation: 17
#include <stdio.h>
int main() {
int test[3];
int i;
test[0]=5;
test[1]=10;
test[2]=7;
printf("array size: %d\n",sizeof(test));
sortArray(test);
for(i=0;i<sizeof(test);i++) {
printf(" %d ", test[i]);
}
printf("\n");
}
void sortArray(int number[]) {
int i,j,a;
int n = 5;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (number[j] < number[i]) {
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
}
The array I am having problems with is "test" When I run the program the "size" is always a multiple of 4 of the intended size. ex: test[3] would output a size of 12. What am I doing wrong? I am using code::blocks as an ide also.
Upvotes: 1
Views: 304
Reputation: 9821
sizeof
returns the memory size of what you pass it. The return value is...
measured in the number of char-sized storage units required for the type
In a typical 32-bit system, a char
is one byte and int
is four bytes so you'll get a multiple of four for an array of type int
.
If you'd like the length of the array, just divide by the size of the type:
int a[3];
size_t n = sizeof(a) / sizeof(a[0]);
Note: As dbush mentioned in the comments below:
...this only works if the array is not a paramerer to a function. In that case the array decays to a pointer and sizeof(array) evaluates to the size of a pointer.
Upvotes: 5