Home  >  Article  >  Backend Development  >  How Can I Determine the Size of a C Array Passed as a Function Parameter?

How Can I Determine the Size of a C Array Passed as a Function Parameter?

DDD
DDDOriginal
2024-11-24 08:17:10565browse

How Can I Determine the Size of a C   Array Passed as a Function Parameter?

Determining Array Size in C Function Parameters

In C , arrays are implicitly converted to pointers when passed as function parameters. This means that the size information is lost, and direct access to the array's size within the function is not possible.

In your code snippet:

void makeVectorData(float p_vertData[]) {   
 int num = (sizeof(p_vertData)/sizeof(int)); 
}

sizeof(p_vertData) retrieves the size of the pointer to the array, not the array itself. Since a pointer requires 32 bits (on a 32-bit system), num will be equal to 1, regardless of the array's actual size.

Solution:

To access the array's size, you can pass a separate parameter indicating the size:

void makeVectorData(float p_vertData[], int size) {   
 int num = size; 
}

In the caller, you would then specify the array's size as an argument:

makeVectorData(verts, sizeof(verts) / sizeof(float));

The above is the detailed content of How Can I Determine the Size of a C Array Passed as a Function Parameter?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn