Reputation: 35
i am new to c, i am trying to make a simple code in which i replace the vowels of an input with the * character... i am having trouble with the array (i am mainly familiar with python only using c now.)
#include <stdio.h>
char* main() {
int c;
char* vowels[] = {'a', 'e', 'i', 'o', 'u'};
while( 1 ) { // means: true
c = getchar();
if(c == EOF) break;
if(c = vowels) putchar('*');
else putchar(c);
}
}
i keep receiving the same error message: novowels.c:5:41: note: (near initialization for ‘vowels[4]’) novowels.c:10:12: warning: assignment makes integer from pointer without a cast [-Wint-conversion] if(c = vowels) putchar('*'); ^
.... please help, i can't quite figure out how do complete this program of replacing vowels with *
Upvotes: 1
Views: 13054
Reputation: 320501
Firstly, char *main()
is illegal in C. It should be int main()
.
Secondly, 'a'
and the like are integer constants in C. You cannot use them to initialize and array of char *
elements. If you wanted a char
array you should have declared it as
const char vowels[] = {'a', 'e', 'i', 'o', 'u'};
If you wanted a string array you should have declared it as
const char *const vowels[] = {"a", "e", "i", "o", "u"};
Finally, it is completely unclear what you were trying to say by c = vowels
. If you want to check whether c
is in vowels
array, keep in mind that there's no core language feature that can do it for you (and certainly not the =
operator). You have to implement the check manually or use an applicable library feature.
For example, one possible way to check it is
const char vowels[] = {'a', 'e', 'i', 'o', 'u'};
...
if (memchr(vowels, c, sizeof vowels) != NULL)
putchar('*');
Alternatively, it can be expressed as
const char *const vowels = "aeiou";
...
if (strchr(vowels, c) != NULL)
putchar('*');
Upvotes: 2
Reputation: 133577
The problem is that you are not comparing anything in c = vowels
. You are assigning to c
the address of the array vowels
(which is a pointer indeed).
Probably you wanted to check equality between c and one of the vowels but you must use the []
operator since vowels
is an array, an index, and a different operator (comparison, which is ==
). Something like:
if (c == vowels[2])
but then vowels should be a char[]
not a char*[]
.
Upvotes: 0
Reputation: 93014
First of all, your program contains a typo. ==
is comparison whereas =
is assignment. Instead of this line
if(c = vowels) putchar('*');
you probably meant to write
if(c == vowels) putchar('*');
but even that is incorrect. You cannot use the ==
operator to test for membership. To test for membership, you could use the strchr()
function from <string.h>
:
if (memchr(vowels, c, sizeof vowels) != NULL) putchar('*');
You can read here about what memchr
does.
Lastly, as AnT
already remarked, main
shouldn't return a char*
. The main
function must return an int
in a strictly conforming C program. Change the line
char* main() {
to
int main() {
to fix this.
Upvotes: 0