Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

arrays - array_length in C

I wrote an array_length function like this:

int array_length(int a[]){
    return sizeof(a)/sizeof(int);
}

However it is returning 2 when I did

unsigned int len = array_length(arr);
printf ("%i" , len);

where I have

int arr[] = {3,4,5,6,1,7,2};
int * parr = arr;

But when I just do

int k = sizeof(arr)/sizeof(int);
printf("%i", k);

in the main function, it returns 7.

What is the correct way to write the array_length function and how do I use it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Computing array lengths, in C, is problematic at best.

The issue with your code above, is that when you do:

int array_length(int a[]){ 
    return sizeof(a)/sizeof(int); 
} 

You're really just passing in a pointer as "a", so sizeof(a) is sizeof(int*). If you're on a 64bit system, you'll always get 2 for sizeof(a)/sizeof(int) inside of the function, since the pointer will be 64bits.

You can (potentially) do this as a macro instead of a function, but that has it's own issues... (It completely inlines this, so you get the same behavior as your int k =... block, though.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...