Here is an example of what I am trying to do:
#include <stdio.h>
FILE* f;
const char* getstring()
{
f = fopen ("hello.txt", "r");
char x[200];
for (int i = 0; i < 200; i++) x[i] = 0;
for (int c = getc(f), i = 0; (c != EOF) && (i < 200); c = getc(f), i++)
x[i] = c;
fclose(f);
printf ("getstring(): x = %s", x);
const char* y = x;
printf ("getstring(): y = %s", y);
return y;
}
void printstring (const char* string)
{
printf ("%s", string);
}
int main()
{
printstring(getstring());
printf ("\nprintf: %s", getstring());
return 0;
}
and the output is:
getstring(): x = Hello World
getstring(): y = Hello World
���getstring(): x = Hello World
getstring(): y = Hello World
printf: ��������
I don't know why the printstring()
function is outputting nothing and printf
is outputting random data or why there is a bit of random data at the end of the string
when I use the printstring()
function.
Is there any way to fix this and what am I doing wrong?