0

I am trying to move some c code into the the separate function. The program counts the length of the line in the file.

#include <stdio.h>

int main()
{
    const int max = 255;
    int counter = 0;
    FILE *f1 = fopen("maps/map1.txt", "r");
    char buff[max];

    while (fgets(buff, sizeof (buff), f1))
    {
        counter++;
    }
    printf("%d\n", sizeof (buff));  // 255
    printf("%d\n", counter);        // 23
    fclose(f1);
    return 0;
}

Counter indicates 23, which is the correct result and the size of the buff variable is 255, as declared.

These simple implementations were moved to a separate function getLineWidth(). Unfortunately, I can't get the correct results.

#include <stdio.h>

int getLineWidth(char * buffer, FILE * file);

int main()
{
    const int max = 255;
    int counter = 0;
    FILE *f1 = fopen("maps/map1.txt", "r");
    char buff[max];
    printf("%d\n", getLineWidth(buff, f1));          // 299
    fclose(f1);
    return 0;
}

int getLineWidth(char * buffer, FILE * file){
    int counter = 0;
    printf("%d\n", sizeof (buffer));                // 4
    while (fgets(buffer, sizeof (buffer), file))
    {
        counter++;
    }
    return counter;
}

The size of the buffer variable is 4, which probably indicates the size of the char, not the size of the array buff passed to the function.The function also returns an incorrect result - 299.

Please help me with this part of the code and show me where I made the mistake.

pobu
  • 402
  • 1
  • 5
  • 13
  • `sizeof(char*) == 4`. – Mateen Ulhaq Sep 22 '19 at 11:55
  • 1
    `sizeof (buffer)` returns the size of the pointer. To know the size of the buffer, you have to pass it as an additional parameter. – Paul Ogilvie Sep 22 '19 at 11:56
  • @MateenUlhaq, you're right, this question has already an answer in How to find the 'sizeof' (a pointer pointing to an array). Thanks! – pobu Sep 22 '19 at 12:10
  • @PaulOgilvie, as you have written, I have passed the size of the buffer as an additional parameter. int getLineWidth(char * buffer, FILE * file, unsigned int bufferSize); This works perfect. Thanks! – pobu Sep 22 '19 at 12:11

0 Answers0