0

I have proble. I have this code, first part with while works I mean good, because by debug code (I print what is save i array, and is looks good). But in for in array inst what i want.

I file I have names in this format:

Peter News
Martin Clear
.
.
.

And my code print in for only last line. I try print other lines in array but in first or last is only last line. I try everthink but it not works.

Here is simple code:

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

int main()
{
    FILE *soubor;
    char radek[80];
    char *data[100];
    int pos = 0;
    int i;

    soubor = fopen("names.txt","r");

    while(fscanf(soubor,"%[^\n]", radek) != EOF){
        getc(soubor);
        data[pos] = radek;
        printf("%d radek = %s pole = %s \n", pos, radek, data[pos]); // debug
        pos++;
    }

    for(i=0;i<100;i++){
        printf("%s \n",data[i]);
    }

    return 0;
}
1
  • data[pos] = radek; , Its contents will be the last one and the same all Because're just copying the pointer. Commented Apr 20, 2014 at 10:05

1 Answer 1

1

Unfortunately, C might not be very intuitive to use in this regard if you don't know it well.

You are storing the individual lines in the radek buffer and overwriting it with each new line. In data, you are just saving the same pointer to radek again and again, therefore at the end, you just print the last contents 100 times.

You would need to use strdup() to store it like this:

data[pos] = strdup(radek);

This will allocate a copy of the string in radek on the heap and do what you need.


But there are more problems then, like you should release the memory with free() after use to be correct, also using statically sized buffers is dangerous with regard to buffer overflows, there is not much error handling etc.

You might want to look e.g. at the answer here which has an implementation of dynamic storage for text file lines.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.