user1747781
user1747781

Reputation: 35

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]?

Upvotes: 1

Views: 2456

Answers (3)

January
January

Reputation: 17090

It's a bit of a mess.

temp is an array of pointers to char. You assign the pointer to temp to the first, second etc. element of that array. That said, this is always the same value, since temp itself doesn't change, and it's contents gets overwritten every iteration of the loop.

Use strncpy() to copy from one string to another.

Upvotes: 0

wallyk
wallyk

Reputation: 57774

There are several problems. I did not look at moep() at all, only main().

You probably did not intended to declare tmp as:

 char* tmp[1];

This declares a pointer, but does not point anywhere. Accessing the second element in it is not "kosher" because it is declared to be one element. (But it doesn't matter because the array is not allocated.)

Probably you meant

 char  tmp[2];

This allocates a space for two characters.

Upvotes: 0

Julian
Julian

Reputation: 852

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.

Upvotes: 1

Related Questions