0

i've looked through quite a few questions of 2-d malloc'd arrays already but bascially for whatever reason i cannot find a solution.... my google fu sux sorry =(. been using the site all day for syntactual help though thanks to everyone who helps here! =)

anyways i cant seem to get this fscanf to work =/ if someone could help me it would be much appreciated because i cant see any error at all but i know there is one because it is at this point that my program crashes.

    array1 = (int**)malloc((c)*sizeof(int*));
        int a = 0, i = 0;
        for (a = 0; a < c; a++){
            array1[a] = (int*)malloc((c+1)*sizeof(int));

        }
    a=0;

    for(a = 0; a < c; a++){
                for(i = 0; i < c; i++){
                fscanf(ifp, "%d", array1[a][i]);

    }
    }

where c is the maximum size of the array needed. in this case it is set to 3 but i do need it as a variable

  • "I've looked through quite a few questions" - [Not enough.](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) –  Feb 08 '13 at 06:34

5 Answers5

5

When using the scanf family of function to read a value, the destination needs to be a pointer. array1[a][i] is not a pointer, it an actual value (which scanf will treat as a pointer and you now entered the territory of undefined behavior).

What you want is &array1[a][i].

PS. You should not cast the returned value of malloc.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • ok i definitely missed out on something conceptual then. i thought the array[i][j] syntax is a pointer for a said address hence the i,j. does it work differently for strings when scanning in then? because my scanning in for strings didnt require an & (ie: address) – user2053368 Feb 08 '13 at 06:37
  • @user2053368 A string already is an pointer, so the address-of operator is not needed there. If you have a pointer `p` and an index `i` then the expression `p[i]` is the _value_ at that index, and to get the address to that value (i.e. the pointer) you use the address-of operator `&` as in `&p[i]`. – Some programmer dude Feb 08 '13 at 06:47
1

fscanf takes pointers, so I would think you need to prepend its third argument with an ampersand. Didn't the compiler warn you about that?

David Grayson
  • 84,103
  • 24
  • 152
  • 189
1

You want:

fscanf(ifp, "%d", &array1[a][i]);
                  ^
PQuinn
  • 992
  • 6
  • 11
1

malloc and other syntext is correct, the issue is in reading the value to array

replace this fscanf(ifp, "%d", array1[a][i]);

with

fscanf(ifp, "%d", &array1[a][i]);

Always enable complier warning, and pay heed to it:)

rajneesh
  • 1,709
  • 1
  • 13
  • 13
0

You need to read this.

Please develop habit of reading manpages. It helps a lot.

Vaibhav
  • 5,749
  • 3
  • 22
  • 18