0

I want to use a function that receive a pointer to an array together with its size and sets all element value to zero.

But the value of the array was checked in the function, the value is not 1234 which should be 1234 if correct, because the input value is 1234.

Just want to know where's the mistake in my following code.

#include <stdio.h>
#include <stdlib.h>

void receive(int *point, const int size);

int main(void) {
    int a;
    int *b;
    scanf("%d", &a);
    b=(int*)malloc(sizeof(int)*a);

    printf("size of input: %d\n", sizeof(b));
    receive(b, sizeof(b));
    free(b);
    return 0;
}

void receive(int *point, const int size) {
    int c=sizeof(*point);

    printf("filling the array to zero");
    int i;
    for (i=0; i<c; i++) {
        printf("\n previous_value:%d\n", point[i]);
        point[i]=0;
        printf(", current_value %d\n", point[i]);
    }
}
Sathish
  • 3,740
  • 1
  • 17
  • 28
user3595689
  • 33
  • 1
  • 6
  • 1
    sizeof(b) is always sizeof(int *) – Mabus Aug 26 '14 at 13:37
  • 1
    you shouldn't cast the result of `malloc()` – Apoorv Aug 26 '14 at 13:40
  • There are several issues: you're casting the return of `malloc` (minor issue), `c = sizeof(*point);` is the same as `c = sizeof *point;` is the same as `c = sizeof(int);`, to assign the actual value that a pointer points to you need `c = *point;`. `scanf("%d", &a);` is not safe, and so on, and so forth – Elias Van Ootegem Aug 26 '14 at 13:42
  • Another issue is that uninitialized values are being read (displaying `point[i]` before ever setting it) – M.M Aug 26 '14 at 13:51

1 Answers1

1

I changed a few incorrect statements, the resulting code is:

#include <stdio.h>
#include <stdlib.h>

void receive(int *point, const int size);

int main(void) {
    int a;
    int *b;
    scanf("%d", &a);
    b= malloc(sizeof(int)*a); //removed implicit declaration of malloc return value

    printf("size of input: %d\n", a);
    receive(b, a); //changed sizeof(b) to a as second argument of function
    free(b);
    return 0;
}

void receive(int *point, const int size) {

    //removed int c = sizeof(*point); unnecessary statement
    printf("filling the array to zero");
    int i;
    for (i=0; i<size; i++) {              //substituted c with size
        printf("\n previous_value:%d\n", point[i]);
        point[i]=0;
        printf(", current_value %d\n", point[i]);
    }
}
Igor Pejic
  • 3,658
  • 1
  • 14
  • 32