For practical purposes does this malloc() code initialize a variable size array?

73 views Asked by At

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).

1

There are 1 answers

2
ikegami On BEST ANSWER

Not quite. It's a pointer, not an array. sizeof(VarArr) will return the size of the pointer. &VarArr will return the address of the pointer. etc.

You could consider it to be a pointer to the first element of an array.

int *p = malloc( sizeof( int ) * n );

is similar to

int a[ n ];
int *p = a;   // int *p = &( a[0] );

Still, there are differences. The memory allocated with malloc must be manually freed, but that also means it can outlast the scope in which the allocation occurred.

int *f( size_t n ) {
   int *p = malloc( sizeof( int ) * n );
   return p;  // ok, but don't forget to free the memory later.
}
int *f( size_t n ) {
   int a[ n ];
   int *p = a;   // int *p = &( a[0] );
   return p;     // Not ok. (See footnote 1.)
}

  1. Technically, returning a pointer to an automatic variable is valid, but dereferencing the returned pointer isn't.