-1

I am studying C programming. I want to find a middle point of array without knowing about length of it. If length of array is 6, middle point must be 4th, but I have an error and I don't know what it is. Here is my code:

    int *a =(int *) malloc(sizeof(int) * n); 

    int i;
    for( i = 0; i < sizeof(a); i++)
        scanf("%d",&a[i]);

Anyone can help, thank you.

user3376115
  • 59
  • 1
  • 1
  • 6

2 Answers2

10

scanf is reading into an address, so:

scanf("%d",a[i])

should really be:

scanf("%d", &a[i])

And do not forget to free the memory when you're done. (For tiny applications like this it does not matter, but it is a good habit if you get used to it when you are stepping out from the learning phase and getting into the real life programming)

And also: sizeof(a) is the size of the pointer, not the size of the memory allocated the pointer points to (as correctly pointed out in the other answer).

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
  • Also, `` should be included; and if the `scanf` fails then the code may try to print uninitialized memory, so it'd be a bit safer to use `calloc` (in lieu of doing proper error checking) – M.M Apr 22 '14 at 12:50
  • i just modified it and still get the wrong result , please help – user3376115 Apr 22 '14 at 12:56
  • @fritzone: Add something about the allocation and element_count errors from the comments? Because this way it does not actually even try to answer the question. – Deduplicator Apr 22 '14 at 13:00
3

This is wrong: for( i = 0; i < sizeof(a); i++). Here sizeof(a) will return size of the int pointer, likely 4 or 8 on your system. In general, don't use sizeof to determine the element count of an array, use separate variable instead.

You'll want to use for( i = 0; i < n; i++) instead.

user694733
  • 15,208
  • 2
  • 42
  • 68
  • Using sizeof to determine the element count of an ***array*** is good practice, it allows dropping magic constants. You meant *pointer to array*. – Deduplicator Apr 22 '14 at 13:04
  • @Deduplicator In my experience using regular constants is always better than `((sizeof(a)/sizeof(a[0]))` -hack, especially for beginners that do not grasp difference between the array/pointer. Also, I'm not sure what you mean with "pointer to array". – user694733 Apr 22 '14 at 13:08
  • Using regular constants is ok, unless you are talking about arrays sized to fit their initialisers. To make my other point clearer, change that to pointer to multiple `int`, so `int*`. (Bad idea of me to mix datastructures and C types without explicitly differentiating) – Deduplicator Apr 22 '14 at 13:15