0

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;
}
  • 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. – Daniel Pryden Sep 03 '18 at 00: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. – Daniel Pryden Sep 03 '18 at 00: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] – Wan Afifi Wan Zain Sep 03 '18 at 00: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). – Daniel Pryden Sep 03 '18 at 00:24
  • @WanAfifiWanZain does the reply I put solve your question? Feel free to ask more questions. – Andy J Sep 03 '18 at 02:47
  • `char` means a single character – M.M Sep 03 '18 at 02:50

1 Answers1

3

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;
}
Andy J
  • 1,479
  • 6
  • 23
  • 40
  • 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 Afifi Wan Zain Sep 03 '18 at 00:12
  • 1
    @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. – Daniel Pryden Sep 03 '18 at 00:20