Reputation: 43
This is probably a really newbie question, but I really couldn't apply any of the other answers to my case.
Say that I have this chunk of code:
int sizemes=0;
char letrarand()
{
int sizemes = 31;
char mesaleat[31] = { ' ' };
char *pMesaleat;
pMesaleat = mesaleat;
int numaleat = 0, i=0;
int randascii = 0;
srand(time(NULL));
for (i = 0; i < 31; i++)
{
numaleat= rand() % 26;
randascii = numaleat + 65;
*(pMesaleat+i) =randascii;
printf("%c \t",*(pMesaleat+i));
}
return 0;
}
Where letrarand is a function that will create an array of 31 elements and assign a random capital letter to each one of those elements. Right now that works, but I want to be able to adjust the size of the array according to the variable sizeofmes, so that if that variable(which is outside of the function) is 15 the array will have 15 elements and so on. For some reason, i can't do that, any ideas?
Upvotes: 0
Views: 73
Reputation: 1271
You declare sizmes
twice, which you don't want to do. The compiler will not know which one to use. You should also declare your pointers outside of the function if you're going to need them later. Either way, you want to make sure you Free
them when done to avoid memory leaks. Declare and initialize them outside of the function, and then utilize it within, like below:
int sizemes = 31;
char *pMesaleat;
char letrarand()
{
char mesaleat[sizemes] = { ' ' };
pMesaleat = mesaleat;
int numaleat = 0;
int randascii = 0;
srand(time(NULL)):
for (int i = 0; i < sizemes; i++)
{
numaleat= rand() % 26;
randascii = numaleat + 65;
*(pMesaleat+i) = randascii;
printf("%c \t",*(pMesaleat+i));
}
return 0;
}
if (pMesaleat)
Free(pMesaleat);
Upvotes: 0
Reputation: 121387
C99 supports variable length arrays (it's optional in C11 and you can check if it's not supported using the macro __STDC_NO_VLA__
).
So, you can do:
int sizemes = 31;
char mesaleat[sizemes];
If your implementation doesn't support VLA (or using C89) then you can resort to malloc()
:
char *mesaleat = malloc(sizemes * sizeof *mesaleat);
if (!mesaleat) {
/* error */
}
and so on.
Note: Call free()
on mesaleat
once you are done with it.
Upvotes: 4