Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a string in a function (C)

Tags:

c

string

I have this small 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);
}

were is the error? Why i can't pass str to 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 ===|
like image 907
Lc0rE Avatar asked Jul 10 '12 17:07

Lc0rE


1 Answers

Your code has at least 3 problems.

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

void invert(char *str)

And you won't need to dereference when passing the argument:

invert(str);

Also note that you've mis-typed the name of the function in your function prototype: you've called it inverti there. The name in the prototype must match the name in the function definition later in the code.

You'll also need to change the argument type in your corrected and renamed function prototype:

void invert(char *str);

Your code has one additional problem: you're iterating over the string using SIZE. SIZE is the maximum size of your array, but not necessarily the size of your string: what if the user types in only 5 characters? You should review and use the function strlen to get the actual length, and in your loop, only iterate over the actual length of your string.

like image 134
pb2q Avatar answered Sep 25 '22 01:09

pb2q