0

Hi there, could I please get some guidance? I'm struggling with printing values from my array. What readFile function does is that it opens .txt file and return me line which I choose. It's working as you can see on the picture, which I put under this snippet of the code, but when I want to print values of that array individually, it always gives me the last value and I don't get why, so my question is how to fix this or if it's there another way how to do it. Thanks a lot! I tried to do my best to describe it correctly.

randomNumber function is just a simple generator with max and min limit.

int main()
{
    long output[500]; 
 
    srand(time(NULL));  
     
    for (int w = 0; w < words; ++w) {

        int randFile = randomNumber(7, 4);
        int randLine = randomNumber(500, 0);

        output[w] = readFile("C:\\Users\\Snowden\\Desktop\\coursework\\" , randFile, randLine);
        printf("\nstdout\t-> %d %s" , w + 1 , output[w]);
    }

    printf("\nstdout\t-> Your array is: %s-%s-%s-%s-%s" , output[0] , output[1], output[2], output[3], output[4]);

}

Output of my program

Barmar
  • 741,623
  • 53
  • 500
  • 612
MH99
  • 15
  • 5
  • `output` should be a `char` array and you should `printf` `char`acters with the `%c` format specifier. – Fiddling Bits Nov 10 '20 at 17:55
  • Why are you printing a `long` value (`output[x]`) with a `%s` specifier. What does `readFile` actually return? A pointer? – Adrian Mole Nov 10 '20 at 17:57
  • This is that readFile function.. https://imgur.com/a/vadvDAL – MH99 Nov 10 '20 at 17:59
  • Returning a local array causes undefined behavior. – Barmar Nov 10 '20 at 17:59
  • When I put there just char, instead of long, it doesn't print me anything. I'm beginner, so it's bit confusing for me. – MH99 Nov 10 '20 at 18:01
  • Ohh, so there is no way for me to fix this? >. – MH99 Nov 10 '20 at 18:01
  • @MH99 - `readFile` returns a `char *` - a pointer to the first character in a string. Each `output[w]` has a type of `long`, which isn't a string. To do what you want, you will need to declare `output` as a 2D array of `char`, such as `char output[500][L+1]`, where `L` is the length of the longest line you intend to store. If the longest line is 80 characters, then your declaration needs to be `char output[500][81];`. Then you will need to *copy* the result of `readFile` to each element like so - `strcpy(output[w], readFile(...));`. – John Bode Nov 10 '20 at 18:06
  • Once you do that, the rest of your code should work as intended (modulo any typos or similar errors). – John Bode Nov 10 '20 at 18:07
  • thanks a lot! its working:) cant imagine where id be without you:D – MH99 Nov 10 '20 at 18:14

0 Answers0