this question has answer here:
when run code gives me segmentation fault error.
#include <stdio.h> #include <stdlib.h> void function(int **a); void main() { int *a = null; int = 0; = (int *) malloc(70 * sizeof(int)); function(&a); (i = 0; < 10; i++){ printf("a : %d\n", a[i]); } free(a); } void function(int **a){ int = 0; (i = 0; < 10; i++){ *a[i]=i*2; } }
*a[i]=i*2; should be
(*a)[i]=i*2; because need dereference pointer before applying array subscript operator([]). in current code, [] has more precedence dereference operator(*) per operator precedence table. need parenthesis.
other things note:
- in c, don't cast result of
malloc - always check result of
mallocsee if successful
have been simpler if pass pointer array,i.e, use
function(a); instead of passing address of a , change function's signature to:
void function(int *a) and using
a[i]=i*2; in for loop in function. since a in function points address of first element of array a in main, change make memory a in function points to, reflected in array a in main.
Comments
Post a Comment