c - Allocating a fixed sized object to a pointer (pointing to a struct) without using malloc -
i have pointer struct list* ptr struct contains char , pointer next struct , these used array of structures so:
list array[setsize]; //setsize defined 20 without using malloc, need initialize list* ptr has elements of array.
i have tried following , segmentation fault. believe utterly misunderstanding how pointers work. (i haven't touched c in long while)
int j = 0; ptr = sizeof(array[j]); //i thinking allocate space for(j; j < setsize; j++) array[j].next = array[j+1].next; ptr = array; //i thought point beginning of array i have looked @ lot of sites c , linked list. had books don't give enough detail particular use of pointers or structures. have been trying while sure missing something.
i need understand going wrong , direction head towards.
thanks , help.
below re-post more code:
//this should initialize array ptr contains array elements void initialize ( list array[] ) { int j; for(j = 0; j < setsize - 1; j++){ array[j].next = array[j+1].next; //using & not seem work, don't use array[j].next = null; } ptr = &(array[0]); } later on using in own malloc function (which seg fault happens)
//this should allocate new list cell in array list* my_malloc () { list* temp; temp = ptr; if(ptr = 0) {printf("empty!\n"); return;} else{ //the next line creates seg fault ptr = (*ptr).next; } return temp; } list* cell ( char n, list* next ) { list* x = my_malloc(); x->value = n; return x; x->next = next; return x; } main ( void* argv, int argc ) { initialize(array); list* x = nil; char ch = a; int i; ( = 0; < setsize; i++ ) x = cell(ch,x); ( = 0; < 10; i++ ) { list* y = x->next; my_free(x); //this own free function x = y; }; ( = 0; < 10; i++ ) x = cell(ch,x); }
i think want:
#define array_length (20) struct list { char ch; struct list* next; }; struct list array[array_length]; // array's memory allocated this, no need use malloc struct list* ptr = &(array[0]); // ptr points 1st item in array int j; // i'm declaring 'j' outside of loop in case using c , not c++ for(j=0 ; j < array_length-1 ; j++) array[j].next = &(array[j+1]); // .next of jth item in array points following item array[j].next = null; // assign .next of last item null, know when have reached end of array when traversing it. note for-loop executed (array_length - 1) items, not array_length items, since array[j+1] out of bounds in last iteration.
now have ptr pointing 1st item in array, can traverse through like:
struct list* curitem; // iterator traverse array curitem = ptr; // initialize iterator point 1st item while(curitem != null) // note this, don't need know length of array { printf("current item's .ch %c\r\n", curitem->ch); // don't forget include header printf curitem = curitem->next; }
Comments
Post a Comment