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; }

1st Jan 2020, 11:14 AM
Ashutosh B. Rajan
Ashutosh B. Rajan - avatar
10 ответов
+ 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.
1st Jan 2020, 11:18 AM
HonFu
HonFu - avatar
+ 5
And you should be using `char` instead of `int`. char str[<size>];
1st Jan 2020, 11:34 AM
Ipang
+ 5
Also refrai from using gets, use fgets instead
1st Jan 2020, 11:48 AM
0x6176696c61
0x6176696c61 - avatar
+ 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...
1st Jan 2020, 12:49 PM
Ashutosh B. Rajan
Ashutosh B. Rajan - avatar
+ 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.
1st Jan 2020, 12:51 PM
Avinesh
Avinesh - avatar
+ 1
Is there any way to create an array which will have size only what is needed to store the input from user?
1st Jan 2020, 12:57 PM
Ashutosh B. Rajan
Ashutosh B. Rajan - avatar
+ 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. 😂
1st Jan 2020, 1:13 PM
HonFu
HonFu - avatar
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
1st Jan 2020, 12:45 PM
Avinesh
Avinesh - avatar
0
Thanks What if i use char str []; Will everything work out? Oh and thanks btw for correcting int
1st Jan 2020, 12:46 PM
Ashutosh B. Rajan
Ashutosh B. Rajan - avatar
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";
2nd Jan 2020, 11:21 PM
Yurii Spichak (Юрій Спічак)
Yurii Spichak (Юрій Спічак) - avatar