MoMoe0 MoMoe0 - 2 months ago 13
C Question

Double pointers, dynamic allocation, and using pointer arrays

So I have narrowed the code to exactly what I need help with. Sorry for the wall of text and scrappy code before.

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

// Function Protype
void test_function(int **ptr2);

// Main Function
int main(void) {
int *ptr1;
int i = 0; // Counter

test_function(&ptr1); // Calling function

for (i = 0; i < 10; i++) {
printf("%d", ptr[i]); // Should print numbers from 0-9
}

return 0;
}

// Custom Function
void test_function(int **ptr2) {
// Variables
int i = 0; // Counter
int j = 0; // Dynamic allocator

*ptr2 = malloc(sizeof(int) * j); // Allocates 10 slots of size int

for (i = 0; i < 10; i++) {
*ptr2[i] = i; // <----- This line gives a segmentation fault error
}

return;
}


So basically, this program should iterate through an array using malloc to assign a dynamic size of j, input the numbers 0-9 and display the 0-9 to the user. However the line in the function
test_function
that is commented is giving me a segmentation fault error.

M.M M.M
Answer

The line *ptr2[i] = i; should be:

(*ptr2)[i] = i;

The way you had it means *(ptr2[i]) which is an error because ptr2 only points to one thing.