So if I have some data type called type, does the following code pretty much initialize a variable size array in C?
type InitValue; //initial value I want every array element to have. For my purposes it is a struct I defined.
int VarSize=5; //variable integer size, set to 5 here arbitrarily
type *VarArr=(type*)malloc(VarSize*sizeof(type)); //My variable length "array"
for (int k=0; k<VarSize; k++){
VarArr[k]=InitValue; //initializing values in "array"
}
Then, for all intents and purposes can I just treat VarArr to be an array of "type" data of length "n"? It seems like it but I heard it technically is something else apparently, and I am definitely not a programmer so I was wondering if the above is bad practice for some computer science reason. Just for more info, I'm doing a very simple "just run this function" program.
Also, are there any IDEs that support C99? I've been using OnlineGDB but it starts throwing weird errors when my VLAs become large and comparing it to Programiz it seems to be a compiler specific error.
I've tried making Visual Studio use C99 for like a half hour before I learned it doesn't support it (despite some yahoo from a university claiming it can be done in the first Google search result I found).
Not quite. It's a pointer, not an array.
sizeof(VarArr)will return the size of the pointer.&VarArrwill return the address of the pointer. etc.You could consider it to be a pointer to the first element of an array.
is similar to
Still, there are differences. The memory allocated with
mallocmust be manually freed, but that also means it can outlast the scope in which the allocation occurred.