如何找到指针数组中元素的数量?
How to find the number of elements in a pointer array?
在使用 malloc 分配的 int 数组指针中查找元素数量的不同方法有哪些?
int* a = malloc(...)
除了从分配中单独跟踪它之外,有零种方法可以做到这一点。
如果将 a
定义为指向数组中第一个元素的普通指针,则不能。另一种方法是使数组的大小成为类型的一部分。因此,您可以将 a
定义为指向 int
的指针,而不是将其定义为指向 int[size]
.
的指针
虽然使用起来有点麻烦,因为您在使用它时需要取消引用它。
示例:
#include <stdio.h>
#include <stdlib.h>
#define Size(x) (sizeof (x) / sizeof *(x))
int main() {
int(*a)[10] = malloc(sizeof *a); // the size made part of a's type
for(unsigned i=0; i < Size(*a); ++i) {
(*a)[i] = i; // note: not a[i] but (*a)[i]
}
printf("%zu\n", sizeof *a); // prints 40 if sizeof(int) is 4
printf("%zu\n", Size(*a)); // prints 10
free(a);
}
在使用 malloc 分配的 int 数组指针中查找元素数量的不同方法有哪些?
int* a = malloc(...)
除了从分配中单独跟踪它之外,有零种方法可以做到这一点。
如果将 a
定义为指向数组中第一个元素的普通指针,则不能。另一种方法是使数组的大小成为类型的一部分。因此,您可以将 a
定义为指向 int
的指针,而不是将其定义为指向 int[size]
.
虽然使用起来有点麻烦,因为您在使用它时需要取消引用它。
示例:
#include <stdio.h>
#include <stdlib.h>
#define Size(x) (sizeof (x) / sizeof *(x))
int main() {
int(*a)[10] = malloc(sizeof *a); // the size made part of a's type
for(unsigned i=0; i < Size(*a); ++i) {
(*a)[i] = i; // note: not a[i] but (*a)[i]
}
printf("%zu\n", sizeof *a); // prints 40 if sizeof(int) is 4
printf("%zu\n", Size(*a)); // prints 10
free(a);
}