Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - How to get array size within function?

I am having trouble finding a way to get the array size from within a function. Here is my code:

#include <stdio.h>

void printBuff(char *buf);
int main()
{
    char arr[12] = "csdlnclskjn";
    printf("Array size: %d, element size: %d. ",sizeof(arr), sizeof(arr[0]));
    printBuff(arr);
    return 0;
}

void printBuff(char *buf){
    printf("Array size: %d, element size: %d.",sizeof(buf), sizeof(buf[0]));
}

As seen above, printBuff does the same as the second line in the main function. However, the outputs are different:

Array size: 12, element size: 1. Array size: 4, element size: 1.

Thinking about it, I understand why the output is 4 in the printBuff() method. In fact, arr is a pointer to the first element of the array. On a 32-bit architecture, sizeof(arr) will then return 4, on 64-bit one it will return 8. What I do not understand is why sizeof(arr) returns the size of the array instead of the number of bytes of the pointer when used in the main() function. After all, arr, when invoked inside main(), is still a pointer, right?

So my questions are:

  1. How come sizeoff() is interpreted differently depending on the context in which it is used? What does this depend on?

  2. How to get the actual array size (number of elements in array) from within a function, without passing the size as an argument, without using methods such as iterating over the array while incrementing a counter until '' is reached - just the simplest way to get array size regardless of the context.

  3. Incidentally, where does the compiler/system responsible for remembering the size of the array store the size of the array? How is it associated with the array and how is it retrieved?

I wanted to iterate though an array using sizeof(buf), / sizeof(buf[0]) as the size of the array but apparently that is not possible.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

so here are my answers for your questions:

  1. The array is "converted" into char* type when passed into the function (with the char* parameter).
  2. AFAIK there is no such way. You could use strlen function for strings. Otherwise, you have to pass the length as parameter.
  3. See How does an array pointer store its size?

Don't use sizeof(buf)/sizeof(buf[0]) to get length of an array when passing array parameters. See this. for more information.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...