I'm trying to see if it is possible to make an array in C that has no definite size. I came up with this idea when I woke up so I programmed it, and surprise surprise! It made an error... Here is my C code:
#include <stdio.h>
#include <stdlib.h>
struct arraylistInt
{
long length;
int (*arrayPtr)[];
void (*increaseLenArraylistIntPtr)(struct arraylistInt, long);
void (*setArraylistIntPtr)(struct arraylistInt, long, int);
int (*getArraylistIntPtr)(struct arraylistInt, long);
void (*initArrayListIntPtr)(struct arraylistInt, long);
};
void increaseLenArraylistInt(struct arraylistInt self, long sizeInc)
{
int localArray = *self.arrayPtr;
free(self.arrayPtr);
self.length += sizeInc;
self.arrayPtr = (int*) malloc(4 * self.length);
for(long i = 0; i < (self.length - sizeInc); i++)
{
*self.arrayPtr[i - 1] = localArray[i - 1];
};
for(long i = self.size - sizeInc; i < self.size; i++)
{
(*self.arrayPtr)[i - 1] = 0;
}
}
int getArraylistInt(struct arraylistInt self, long index)
{
return (*self.arrPtr)[index];
}
void setArraylistInt(struct arraylistInt self, long index, int value)
{
if(index <= self.length)
{
(*self.arrayPtr)[index] = value;
}
else if(index - self.length == 1)
{
(*self.increaseLenArraylistIntPtr)(self, 1);
self.arrayList[self.length - 1];
}
else
{
printf('index size exceeds threshold, line 41.');
};
}
void initArrayListInt(struct arraylistInt self, long defaultLength)
{
self.length = defaultLength;
self.arrayPtr = (int*) malloc(self.length * 4);
self.increaseLenArraylistIntPtr = &increaseLenArraylistInt;
}
int main()
{
printf("Hello world!\n");
struct arraylistInt newArraylist;
newArraylist.initArrayListIntPtr = &initArrayListInt;
(*newArraylist.initArrayListIntPtr)(newArraylist, 2);
newArraylist.setArraylistIntPtr(newArraylist, 1, 43);
printf('The value at index 1 is: %i', (*newArraylist.getArraylistIntPtr)(newArraylist, 1));
return 0;
}
When I run it, I get this error:
22 error: invalid use of array with unspecified bounds
I know the cause, but I can't think of any loopholes that can fix this. Is there an actual solution? Thanks in advance btw.
Aucun commentaire:
Enregistrer un commentaire