0

In this program when I'm using "char* str" instead of char str[80] its printing null instead of strings. Why?

#include<stdio.h>

 int main(){
     char str[45];
     FILE* dic = fopen("small", "a+");
     if(dic==NULL)
     {
         printf("cant open");
         return -1;
     }
     for (int i=0; i<6; i++)
     {
         if(fscanf(dic, "%s", str) == EOF)
         {
             printf("END");
             break;
         }
         else
         {
             printf("%s\n", str);
         }
     }
     fclose(dic);
     return 0;
 }
0

If you do char* str; you are trying to create a pointer to a null string. This didn't even compile for me. Did you do something slightly different? However, when you do char str[45]; you are allocating space in memory that can be initialized and changed over and over, which is exactly what you need.

I tested your code and it did print "END" for files with files less than 6 lines (1 word per line). If it was 6 or more, then "END" wouldn't print. However, it didn't print a '\n' line feed after END, so it was immediately followed by the operating systems' new line prompt. Is it possible you didn't notice it?

It's also possible that the 'small' file has been changed or that you are editing it in one directory and the program is processing a different copy in another direcory, or your are similarly editing one copy of the program and running another version.

If this answers your question, please accept this answer to remove the question from the unanswered question pool. Let's keep up on forum housekeeping. ;-)

3
  • well yeah you were right I did not notice END being printed. Sorry to bother you for that but apropos of my first doubt I guess you would be compiling it in cs50 appliance, that is why it wouldn't even get compiled as appliance treats even warnings as errors. Nonetheless, if you would do "str = NULL" just after declaring str it would compile and run. And, yes I understand it now why it is printing NULL instead of the expected. As str is pointing to NULL and not some actual memory address it can't place the scanned words to address pointed by str i.e. NULL. Thanks for your hint. Jul 6 '15 at 18:20
  • yeah, I keep forgetting about the flag that converts warnings to errors.
    – Cliff B
    Jul 6 '15 at 18:21
  • char *str; isn't necessarily NULL unless it's a global variable or explicitly initialized to NULL.
    – kzidane
    Jul 6 '15 at 21:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .