-2

What I want exactly is to allocate tab and fill it with some numbers.

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

void prepare_internship(int** tab) {
    *tab = malloc(5 * sizeof(int));
    *(*tab+0) = 1;
}

int main() {
    int** tab;
    prepare_internship(tab);
    printf("%d", *(tab));
    return 0;
}
donjuedo
  • 2,475
  • 18
  • 28
XPRO
  • 31
  • 1
  • 8

2 Answers2

3

You're passing an uninitialized pointer into prepare_internship. What you need instead if you want the function to modify tab is:

int* tab;
prepare_internship(&tab);

But in this case it's better to change your function to have a int* return type and then you can simply call it with tab = prepare_internship();

interjay
  • 107,303
  • 21
  • 270
  • 254
  • I need to take speed typing lessons. ;-) – donjuedo Dec 22 '15 at 14:22
  • hhh Thank you too ☺ but i still don't understand why I should pass an initialized pointer ! – XPRO Dec 22 '15 at 14:26
  • @XPRO You need to pass in the address of an actual variable that you want the function to change. What your code did was pass in an uninitialized address that points to a random memory position. – interjay Dec 22 '15 at 14:28
0

int** tab is not initialized. It should be int* tab and when passed as an argument, passed like this: &tab.

donjuedo
  • 2,475
  • 18
  • 28