Search code examples
ccharfgets

c fgets char array


I have a problem with fgets. I can't save the String "temp" in the if-statement.

The Code:

      1 #include <stdio.h>
      2 #include <string.h>
      3 #include<stdlib.h>
      4 
      5 void moep(char** tmp){
      6         FILE *fp;
      7         fp=fopen("moep", "r");
      8         int line_num = 1;
      9         int find_result = 0;
     10         char* str="jochen";
     11         char temp[512];
     12 
     13 while(fgets(temp, 512, fp) != NULL) {
     14                 if((strstr(temp, str)) != NULL) {
     15                         printf("A match found on line: %d    \n", line_num);
     16                         tmp[find_result]=temp;
     17                         printf("\n%s\n", tmp[find_result]    );
     18                         find_result++;
     19                 }
     20                 line_num++;
     21         }
     22 fclose(fp);
     23 printf("tmp[0]:%s\n",tmp[0]);
     24 tmp[1]="ich funktioniere";
     25 }
     26 
     27 int main(){
     28 
     29         char* tmp[1];
     30         moep(tmp);
     31         printf("%s, %s\n",tmp[0],tmp[1]);
     32         return 0;
     33 }

and moep is:

unwichtig1
jochen g
unwichtig2
unwichtig3

The output:

 /A match found on line: 2

jochen g

tmp[0]:unwichtig3

��Ł�, ich funktioniere


why can't I save "jochen" in tmp[0]?


Solution

  • Assigning to tmp[1] is assigning to random memory, as you're array isn't that big. It will have all sorts of bad side effects - including crashing the program.

    You are also reusing the temp[] array - so that will keep getting overwritten, you need to copy the string if you want to keep it.