1

The program simply reads the file count strings and their length. But the counter p of string gives me a wrong result. If I just print the count p the result will be correct but if I print the element a[i][1] (which is supposed to be p) it gives me a wrong result. For an example in element a[0][1] - it prints 12, where it is supposed to be 1.

int main(int argv,char* argc[]) {

    FILE *f = fopen("d.txt","r");
    int a[700000][1];
    char str[120];
    int i=0,l,p=0,n;
    while (fgets(str,120,f)) {
        l=strlen(str)-1;
        p++;
        a[i][0]=l;
        a[i][1]=p;
        i++;
    }
    // if I printf("%d",p);  result will be correct
    n=i-1;
    for (i=0;i<=3;i++) {
        printf("%d\n",a[i][1]); //result - 12 6 4 8 
    }

    close(f);
    return(0);
}

d.txt

No\0 one\0 is\0 here\0

result will be - 4 2 4 4

6
  • We cannot reproduce this without your input data. Please present your minimal reproducible example as instructed. Commented May 14, 2016 at 15:37
  • 1
    What is this: 'int a[700000][1];' ?? Commented May 14, 2016 at 15:39
  • int a[5][1]; look better? Commented May 14, 2016 at 15:40
  • ...because this 'a[i][1]=p;' is UB. Commented May 14, 2016 at 15:40
  • 2
    @alex_mike no, not really:( The only valid index for the second dimension is [0]. Commented May 14, 2016 at 15:42

1 Answer 1

4

Your problem is this line:

int a[700000][1];

This defines a 2 dimension array of type int, but the 2nd dimension is 1, resulting effectively in a 1 dimension array.

Later on, when you attempt to access elements in the array:

    a[i][0]=l;
    a[i][1]=p;

The first assignment is fine -- it sets the value in memory that is i integers away from the start of the array.

But the second assignment is not correct. The index 1 is beyond the 2nd dimension limit of 1 (0 is the first element, 1 is the second element). Since C does not do run time array limit checking, so this gets translated to setting an element that is i+1 integers away from the start of the array.

If you want a 700000x2 array, the declaration would look like this:

    int a[700000][2];
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.