尝试创建一个通用函数,用于生成任何类型的数组并将大小存储在[-1]、返回大小函数和freearray函数 #包括 #包括 //通用函数,可以创建任何类型的数组,然后将其大小隐藏为[-1]。 void*createArray(int n,int dataTypeSize); //从数组的位置[-1]返回大小 void getArraySize(void*array); //释放数组 void freeArray(void*array); 内部主(空){ 双*数组=0; int size=10; array=createArray(大小,sizeof(double)); if(数组==NULL){ printf(“\n无法分配内存”); } 对于(int i=0;i 您不能使用索引-1,因为它超出了范围

尝试创建一个通用函数,用于生成任何类型的数组并将大小存储在[-1]、返回大小函数和freearray函数 #包括 #包括 //通用函数,可以创建任何类型的数组,然后将其大小隐藏为[-1]。 void*createArray(int n,int dataTypeSize); //从数组的位置[-1]返回大小 void getArraySize(void*array); //释放数组 void freeArray(void*array); 内部主(空){ 双*数组=0; int size=10; array=createArray(大小,sizeof(double)); if(数组==NULL){ printf(“\n无法分配内存”); } 对于(int i=0;i 您不能使用索引-1,因为它超出了范围,c,C,你应该使用struct #include<stdio.h> #include<stdlib.h> //general function that can create an array of any kind and then hide the size of it at[-1]. void * createArray(int n, int dataTypeSize); //returns the size from location [-1] of array voi

你应该使用struct

#include<stdio.h>
#include<stdlib.h>

//general function that can create an array of any kind and then hide the size of it at[-1].
void * createArray(int n, int dataTypeSize);
//returns the size from location [-1] of array
void getArraySize(void * array);
//frees array 
void freeArray(void * array);

int main(void){
    double * array=0;
    int size=10;
    array=createArray(size,sizeof(double));
    if(array==NULL){
        printf("\nmemory could not be allocated");
    }
    for(int i=0; i<size; i++){
        array[i]=i;
        printf("%lf",array[i]);
    }
    printf("\nsize of the array is %lf",getArraySize(array));
    freeArray(array);

}
void * createArray(int n,int dataTypeSize){
    void * array=0;
    array=malloc(n*dataTypeSize+sizeof(int));
    if(array==NULL){
        printf("\nmemory could not be allocated");
        exit(0);
    }
    //moves array up 1
    array=array+1;
    //changes size to the specified datatype and stores it at -1
    array[-1]=(dataTypeSize)n;
    return(array);
}

void getArraySize(void * array){
    return(array[-1]);
}

void freeArray(void * array){
    free(array-1);
}

对于大小,您应该使用正确的类型
size\t

,正如消息所说,您不能取消对空指针的引用。在这种情况下,编译器无法知道数据的大小。您可以先强制转换为
int*
array=array+1;
也是错误的,因为C标准中不允许对空指针执行指针算术。GNUgcc确实允许它,但即使这样,它仍然是错误的,因为它将它视为大小1,您需要按
int
的大小递增。OP在
array=array+1;
索引之前已经完成了
-1
操作。它仍然是错误的,但其目的是让
数组
指针开始一个
int
到实际分配的值中缓冲区。类似于有多少
malloc
实现将头放在数据块之前。@kaylum在您看来这
+1
有什么作用?我认为它没有达到预期的效果。我只是解释OP的意图。根据C标准,它是无效的,但gcc通过将其视为ad的+1来支持这一点衣服。它不是减去4,而是减去1。因为
array
void*
所以
array[-1]
是减去1。所以从技术上讲,它不是越界的,但由于其他原因是错误的。
typedef struct
{
    size_t size;
    size_t elementsize;
    unsigned char data[];
}data_t;


data_t *create(size_t size, size_t elementSize)
{
    data_t *data = malloc(sizeof(*data) + size * elementSize);

    if(data)
    {
        data -> size = size;
        data -> elementsize = elementSize;
    }
    return data;
}

void destroy(data_t *data)
{
    free(data);
}