arrays - C pointer dereference error -
suppose have following code (example):
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> void ex(void *ret, int ret_len, int choice){ if(choice==1){ int *ret = ret; for(int i=0; i<ret_len; i++){ *(ret+i) = i; } } else { int **ret = ret; for(int i=0; i<ret_len; i++){ for(int j=0; j<ret_len; j++){ *(*(ret+i)+j) = i*j; } } } } int main() { int m[10]; ex(m,10,1); printf("%i",m[3]); return 0; }
the goal of function take pointer preallocated memory of 1 or 2 dimensional array.
when compiled , executed code works when choice==1
, otherwise, if run
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> void ex(void *ret, int ret_len, int choice){ if(choice==1){ int *ret = ret; for(int i=0; i<ret_len; i++){ *(ret+i) = i; } } else { int **ret = ret; for(int i=0; i<ret_len; i++){ for(int j=0; j<ret_len; j++){ *(*(ret+i)+j) = i*j; } } } } int main() { int m[100]; ex(m,10,2); printf("%i", m[3][5]); return 0; }
no output ever produced , code seems run forever (note choice not 1 , m proper size)
i under impression casting in ex should change shape of array , allow main index if 2d neither indexing if 1d nor 2d work.
having looked @ comments on question , answers have gathered requirements.
you need generic function takes array of choice
dimensions , initializes values.
this can suit purpose.
void ex(void *_ret, int ret_len, int choice){ if(choice==1){ int *ret = _ret; int i; for(i=0; i<ret_len; i++){ ret[i] = i; } } else { int (*ret)[ret_len] = _ret; int i, j; for(i=0; i<ret_len; i++){ for(j=0; j<ret_len; j++){ ret[i][j] = i*j; } } } }
now how can call it
int main(void) { int first[10]; ex(first, 10, 1); int second[20][20]; ex(second, 20, 2); printf("first[4] = %d\n", first[4]); printf("second[3][4] = %d\n", second[3][4]); }
you can see demo here
Comments
Post a Comment