1

I'm Trying to do some simple c programming that will return the char value. The program is running with no error but, the output of the expected string does not appear. What I expected it will return the Halloworld when i run it.

#include <stdio.h>
#include <string.h>

char screen(char c[]);

int main(){

    char b[] = "Hallo";
    //screen(b);
    printf("%s",screen(b));
}

char screen(char c[]){

    strcat(c, "world");
    return c;
}
6
  • 1
    Does that program even compile? You appear to be attempting an implicit conversion from char[] to char and I would expect a compile-time error from that. Commented Sep 3, 2018 at 0:14
  • More importantly: b is a constant object without enough space for any more data to be appended to it, which means this program is undefined behavior and anything could happen, including nothing at all. Commented Sep 3, 2018 at 0:16
  • yes, the program are compiled but it give the warning like this in the 'screen' function warning: return makes integer from pointer without a cast [-Wint-conversion] Commented Sep 3, 2018 at 0:17
  • 1
    That's a very important warning! (And you probably should be compiling with -Wall -Werror or whatever the equivalent in your compiler would be: don't just ignore a compiler warning like that.) If you don't understand that warning, then that's a good question in itself (but I'm pretty sure it's been asked and answered thoroughly already here somewhere). Commented Sep 3, 2018 at 0:24
  • @WanAfifiWanZain does the reply I put solve your question? Feel free to ask more questions. Commented Sep 3, 2018 at 2:47

1 Answer 1

4

The declaration of strcat() returns a pointer to char (char *). So your function screen() must also.

Another thing is, you can't do this char b[] = "Hallo";, because then the character array b is only large enough to handle Hallo. You'll need it larger than Hallo, and the rest will be filled with 0x00, or NUL. Like so:

48 61 6C 6C 6F 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00

And then after you strcat() the characters world onto the end:

48 61 6C 6C 6F 20 77 6F 72 6C 64 00 00 00 00 00 00 00 00 00

The first left over 0x00 will act as a null terminator when passed to printf().

#include <stdio.h>
#include <string.h>

char* screen(char c[])
{
    strcat(c, "world");
    return c;
}

int main()
{
    char b[20] = "Hallo ";
    screen(b);
    printf("%s",b);

    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

may i know why we must put pointer on the function? while 'int function' or 'float function' will do just fine without using pointer on the function.
@Wan: Because an int is just an int but a string (array of char) is more than just a char. The convention in C is to use a pointer to the first char of the string to represent a string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.