简体   繁体   中英

Calling a function doesn't execute the print statement inside that function

Why is it that my first block of code doesn't output anything while the 2nd block does print out "hi"? I suspect that the program never goes into the test() function in the first block, but I don't know why that happens and how I should fix it.

PS I know that my codes don't really make any sense such as that the return value of the functions should be char *. This is because I haven't completed the function and I am still at the stage of testing what I have written. I think the return value of char * shouldn't be the reason for my problem, but do let me know if it is!

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

char* test(char **strs, int strs_sz){
  printf("%s", "hi");
}

int main(void){
    char *arg[] = {"XX", "YY", "ZZ"};
    char *all = test(arg, 1); 
    printf("%s\n", all);
    free(all);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* fcn(char **para){
    printf("%s", "hi");
}

int main(void){
  char *arg[] = {"XX", "YY", "ZZ"};
  char *s = fcn(arg); 
}

To sum up what was already explained in the comments and fill in some blanks:

When using standard C library functions to work with files ( printf actually works with a file stdout ), the data is first cached in memory, and only written to the actual file when some condition is met:

  • The file is closed
  • The file is fflush ed.
  • The memory buffer is full
  • etc.

In case of stdout , this will happen when the \n character is printed or when your program exists and the file is closed.

However, in your first code snippet you try to dereference (use) a pointer all .
Since you did not write a return statement in your test function, it is impossible to predict what value will end up being stored in all .

So, your program most likely crashes unexpectedly, and thus the buffer never gets written to stdout .

You should never test incomplete functions!
At the very least, build up a skeleton code that makes the function legal, such as a dummy return statement.

Otherwise, you will encounter "undefined behavior", which is another way of saying your program will react in weird and unpredictable ways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM