Passing a String in a Function (C)

I have this little program:

#include <stdio.h> #include <string.h> #include <ctype.h> #define SIZE 30 void inverti (char s); int main () { char str[SIZE+1]; gets(str); printf ("Your imput: "); puts(str); invert(*str); printf ("It works!"); return 0; } void invert (char s) { int i; for (i = 0; i < SIZE + 1; i++) { if (isupper(str[i])) str[i] = tolower(str[i]); else if (islower(str[i])) str[i] = toupper(str[i]); } puts(str); } 

was there a mistake? Why can't I pass str my function?

 In function 'main':| warning: passing argument 1 of 'inverti' makes integer from pointer without a cast [enabled by default]| note: expected 'char' but argument is of type 'char *'| In function 'invert':| error: 'str' undeclared (first use in this function)| note: each undeclared identifier is reported only once for each function it appears in| ||=== Build finished: 3 errors, 1 warnings ===| 
+4
source share
1 answer

Your code has at least 3 problems.

First, and most relevant to your specific question, you declared the argument to your function as one character: char . To pass the string C, declare the argument as char * - a character pointer is a type also used for string C:

 void invert(char *str) 

And you do not need to play when passing an argument:

 invert(str); 

Also note that you typed the function name incorrectly in the function prototype: you named it inverti there. The name in the prototype must match the name in the function definition later in the code.

You will also need to change the type of the argument in the revised and renamed function prototype:

 void invert(char *str); 

There is another problem in your code: you repeat the line using SIZE . SIZE is the maximum size of your array, but not necessarily the size of your string: what if the user enters only 5 characters? You must view and use the strlen function to get the actual length, and in your loop, only iterate over the actual length of the string.

+11
source

All Articles