0
Arrays in C ( why does this program create error when size is not defined for an array (works if size of array is defined)?)
#include <stdio.h> int main() { int str[]=""; int i=0; gets(str); while (str[i] != '\0'){ if (str[i] =='a' || str[i] == 'e' || str[i]== 'i' || str[i] =='o' || str[i] =='u'){ printf("Vowel = %c",str[i]); } else { printf("consonant = %c",str[i]); } i=i+1; } return 0; }
10 Respostas
+ 5
If you don't define the size of a raw array, it will be as long as what you initialize it with.
Since you're just giving an empty string, you won't have storage room to put stuff in.
+ 5
And you should be using `char` instead of `int`.
char str[<size>];
+ 5
Also refrai from using gets, use fgets instead
+ 1
Do i always have to define the size of array ?
If i define the size it limits how much i can sore in it and also some space can be unused if it is too big...
+ 1
If you are declaring an array and initializing at the same time then you do not have to give the size but if you are just declaring it and adding values later then you have to define the size.
+ 1
Is there any way to create an array which will have size only what is needed to store the input from user?
+ 1
You can create a pointer and require memory on the heap and reallocate when the input, taken letter by letter, increases.
Which is obviously relatively annoying.
A higher language like Python does all this stuff for you in the background, so you don't have to think about it. It's like sitting in a robot suit.
In C, you're just you in a muscle shirt and have to do most things with your own hands. 😂
0
Just did what the others mentioned, if you don't know the syntax for fgets() then kindly read about it.
https://code.sololearn.com/cC9VB3qAr334/?ref=app
0
Thanks
What if i use
char str [];
Will everything work out?
Oh and thanks btw for correcting int
0
In general if you don't explicitly specify array size, you should initialize your array during definition. In this case the size of your array will be specified implicitly during compilation.
/*
Size = 6 chars + '\0'
Initialized during compilation
*/
char str[] = "string";