ZeroVash
ZeroVash

Reputation: 558

c - wrong count result in array

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

Upvotes: 1

Views: 120

Answers (1)

Jay Elston
Jay Elston

Reputation: 2078

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

Upvotes: 4

Related Questions