-1

Why modifying ptr has no effect on vector? I'm trying to change value through f function.

void f(int *ptr, int size, int value){
    ptr=(int* )malloc(sizeof(int));
    if(ptr!=NULL){
        int i;
        for(i=0;i<size;i++)
            *(ptr + i) = value;
        }

}

int main (void)
{
  int *vector = NULL;
  f(&vector, 3, 324);
    printf("%p\n", vector);

}
Piotr Wera
  • 49
  • 1
  • 2
  • 7

1 Answers1

5

You are assigning the results of malloc to the parameter ptr, which is local. You should be assigning it to what ptr points to.

void f(int **ptr, int size, int value)
{
  *ptr = (int*)malloc(sizeof(int) * size);
  // Rest of code
}
Matt Houser
  • 33,983
  • 6
  • 70
  • 88
  • 1
    `ptr` is a parameter to your function, so it is a local variable. – Matt Houser Jun 05 '13 at 20:00
  • 1
    @PiotrWera: The formal parameter `ptr` is a distinct object in memory from the actual parameter `vector`, and is local to `f`; changes made to `ptr` in `f` won't be reflected in `vector`. Instead of writing to `ptr`, you need write to what `ptr` *points to*, or `*ptr`. You were most of the way there, but you had the type for `ptr` wrong in your function prototype (should have been `int **ptr`, as Matt has shown). – John Bode Jun 05 '13 at 20:07
  • And on top of all that, he's only allocating space for a single int, then trying to put multiple ints there. – Lee Daniel Crocker Jun 05 '13 at 21:10