从c中的未知类型数组创建指针数组
我需要编写一个函数,用于: 未知类型数组、数组大小和元素大小 并返回指针数组:首先是负值,然后是正值。这就是Iv迄今为止所做的:从c中的未知类型数组创建指针数组,c,arrays,pointers,types,C,Arrays,Pointers,Types,我需要编写一个函数,用于: 未知类型数组、数组大小和元素大小 并返回指针数组:首先是负值,然后是正值。这就是Iv迄今为止所做的: void *mix(void *A, int nElementsA, int sizeOfAnElement) { char** res = (char**)malloc(sizeof(char*)*nElementsA*sizeOfAnElement); char* p = (char *)A; char* bStart = res[0];
void *mix(void *A, int nElementsA, int sizeOfAnElement) {
char** res = (char**)malloc(sizeof(char*)*nElementsA*sizeOfAnElement);
char* p = (char *)A;
char* bStart = res[0];
char* bEnd = res[nElementsA*sizeOfAnElement - sizeOfAnElement];
while (p<(char*)A + nElementsA*sizeOfAnElement) {
if (*(int*)p>0) {
bStart = p;
bStart += sizeOfAnElement;
}
else {
bEnd = p;
bEnd -= sizeOfAnElement;
}
p += sizeOfAnElement;
}
return res;
}
void*mix(void*A、int-nElementsA、int-sizeofan元素){
char**res=(char**)malloc(sizeof(char*)*nElementsA*sizeOfAnElement);
char*p=(char*)A;
char*bStart=res[0];
char*bEnd=res[nElementsA*sizeOfAnElement-sizeOfAnElement];
while(p0){
b开始=p;
bStart+=sizeofan元素;
}
否则{
弯曲=p;
弯板-=Sizeofan元件;
}
p+=Sizeofan元素;
}
返回res;
}
我得到了一堆垃圾,
什么错了?首先:你想做的事是不可能的,也毫无意义 你说你有:
一个未知类型的数组
,因此你可以不访问数组的任何元素。做:
(*(int*)p
表示您假定元素的类型为int
(或兼容)。这显然与未知的类型相冲突
除此之外
这条线
malloc(sizeof(char*)*nElementsA*sizeOfAnElement);
分配太多内存。它只能为每个元素分配一个指针,即
malloc(sizeof(char*)*nElementsA);
固定的:
你能做一个例子来说明你是如何使用/调用这个函数的吗?你想如何解释和处理你不知道的东西?你甚至不知道它有“消极因素”。您当前所做的是将所有内容解释为
int
。您也可以传入一个int
数组。
void *mix(void *A, int nElementsA, int sizeOfAnElement,
int (*isPositive)(const void *)) {
// Allocate a `char*` array containing `nElementsA` pointers.
char **res = malloc(nElementsA * sizeof *res);
// &p[i] == &A[i]
char (*p)[sizeOfAnElement] = A;
// bStart points to the first result element.
char **bStart = &res[0];
// bEnd points to the last result element.
char **bEnd = &res[nElementsA - 1];
// Loop through the array,
// adding &A[i] at the start of the result array if positive,
// else at the end of the result array.
for (int i = 0; i < nElementsA; i++) {
if (isPositive(p[i])) {
*bStart = p[i];
bStart++;
}
else {
*bEnd = p[i];
bEnd--;
}
}
return res;
}
// I added the typedef for more easily understood declarations of `p` and `end`.
typedef char array_alias_t[sizeOfAnElement];
// p's type is the same as in the previous code (char (*)[sizeOfAnElement]).
array_alias_t *p = A;
// p + x == &p[x], and &p[nElementsA] is one element past the end of A,
// which is allowed by ISO C, provided you don't dereference the pointer
// (i.e. *end is not allowed).
for (array_alias_t *end = p + nElementsA; p != end; p++) {
if (isPositive(*p)) {
*bStart = *p;
bStart++;
} else {
*bEnd = *p;
bEnd--;
}
}