0

This is my first time to learn C language. I just want to ask how would you be able to return back a string in C. Here is what I'm doing.

int main()
{
    char input[1] = "";
    input = setChar();
    printf("%s",input);
}

char *setChar()
{
     char *character;
     printf("Enter a new character.\n");
     scanf("%s", &character);
     return character;
}

EDIT: So it's basically I want to have a method that will return a string or character value that will change the value of the string or character from the main method. Is this possible?

3
  • you want to return a string instead of the char?
    – Sim
    Commented Sep 20, 2015 at 4:05
  • 1
    Make question more clear :(
    – DarKnight
    Commented Sep 20, 2015 at 4:54
  • I edited that one. So it's basically I want to have a method that will return a string or character value that will change the value of the string or character from the main method. Is this possible?
    – Sleek13
    Commented Sep 20, 2015 at 19:26

1 Answer 1

1

It isn't actually possible to return a string, because a string is a sequence of values that fits a pattern. We store that sequence of values into a type (an array of characters, typically), and it is that type (or a pointer into that type) that we return.

Your function is usually returning a pointer that points to a string, which is probably what you meant to ask about... and now that I can see what your actual goal is I can guide you in a better direction from the beginning, rather than merely pointing out what's wrong with the program you've posted.

however I need to use char return type and no parameters. Is that possible? like "char *setChar()"

I wrote some code in this answer. Making use of that code, you could write such a function like this:

cbar *setChar() {
    return get_dynamic_word(stdin);
}

With that code, your main function should look something like:

int main(void) {
    char *input = setChar();
    if (input == NULL) {
        exit(EXIT_FAILURE);
    }
    
    printf("%s", input);
    free(input);
}

There are a few things wrong with this program. Let us identify them one line at a time.

int main()

While this might usually work, it doesn't provide the freestanding environment (your OS) with a specific prototype. In the words of the C standard,

The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.

This concept is best demonstrated by the lack of error messages, even when compiling with the strictest of flags indicating that warnings should be errors:

int main() {
    return main(42, 42, 42, 42, 42);
}

So which of these two prototypes (or equivelant) will it choose?

int main(void) { /* ... */ }

int main(int argc, char *argv[]) { /* ... */ }

Technically, the behaviour is undefined.

A quick note about undefined behaviour: Some people will write that a "crash" might occur, instead. Defining undefined behaviour to "crash" is a misnomer; this might very well work as you expect, but that's not a requirement of the C standard. So if you change compilers, or your OS updates, or some other minuscule change occurs (such as user input) then you might start to see your program malfunction.

You should probably stick to one of the two prototypes for main that I mentioned previously.

It seems obvious that you're probably not learning from a book, by the way. K&R (2nd edition) has been tried & tested for decades, and proven to successfully teach thousands of students. Make sure you do the exercises.


char input[1] = "";

A string is a sequence of characters that terminates at the first '\0' (a.k.a. 0, not to be confused with '0' (see the quotation marks) which typically is 48). You might note if you printf("%d\n", input[0]); that the first (and only) character in input is initialised to 0.

How many character values can you store into input? Only one, because you've declared it to be only one character. That means you can only store one kind of string into this array: an empty one.

You need to accommodate for the null (zero) termination of a string, when you decide how long to make your char arrays that store the string. If you were to declare input as char input[256]; (as in other answers), input can store 255 non-zero characters followed by 1 zero character to terminate the string.


input = setChar(input);

This line of code is technically a constraint violation; your compiler should be producing an error message. You can't assign to arrays like that. Not to worry, it's an easy fix because the return value is superfluous; your function modifies the array directly. Use this, instead:

setChar(input);

printf("%s",$input);

You haven't declared any such identifier $input, and in fact since the C standard doesn't require a $ character to exist in the source character set, it would be an error to do so. I think you meant to write this:

printf("%s", input);

scanf("%s", &c);

There are two problems with this:

  • When scanf returns anything other than 1, an IO error might have occured and c might not contain a string (which means you shouldn't lie to printf and tell it to print a non-string as though it's a string... See my note on undefined behaviour). Don't ignore the return value of scanf. Ever.
  • The format directive %s tells scanf that the argument you're giving it is a char *, however using the & operator on a char * produces a char **... You're lying to scanf, which is also undefined behaviour.

You probably meant to write something like:

int x = scanf("%s", c);
if (x == 1) {
    return c;
}
else {
    return NULL;
}

This would give your return value a purpose: You can determine whether or not your function was successful when you call it:

char *str = setChar(input);
if (str == NULL) {
    /* An error occured */
}
else {
    /* c -should- contain a string */
}

I say it should contain a string because there are situations where it might not. Others have mentioned the problem of buffer overflows. Those can be avoided by telling scanf how large your array is, in which case a string can be guaranteed:

char input[256];
int x = scanf("%255s", input);

A question arises as to what happens if a particular word (since %s reads words) is longer than 255 characters. scanf will stop reading, leaving the remainder of the word for the next call to scanf (or getchar, or whatever) to process. If you wanted to discard the remainder of such a word, the code above could be followed up by this:

scanf("%*[^ \n\t]");
puts("NOTE: Input truncated!");

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.