c - How to use dynamic allocation instead of static int? -
int* asciicode(char c1, char c2){ static int asciicode[126]; /code/ /code/ return asciicode; }
can use allocation instead of static int situation ? don't know number of elements of above pointer array ? if yes, how can ?
this example may find useful. array
allocated , used in subsequent calls in order emulate use of static array hold values between calls.
#include <stdio.h> #include <stdlib.h> int* asciicode(char c1, char c2, int *asciicodearr, int size ){ int static counter = 0; if(asciicodearr==null) { asciicodearr = (int *) malloc( sizeof(int)* size); if(!asciicodearr) return null; } printf("c1=%c ",c1); printf("c2=%c ",c2); asciicodearr[counter] = c1; counter = counter + 1; asciicodearr[counter] = c2; counter = counter + 1; return (asciicodearr); } int main(void) { int i; int *array=null; int size = 128; // hold 128 - 7bits standard ascii characters array = asciicode('1', '2', array, size); if(!array){ printf("allocation error!\n"); return -1; } // array = asciicode('3', '4', array, size); printf("\narray content in hex: "); for(i=0;i<4;i++) { printf("%x ", array[i]); } free(array); return 0; }
output:
c1=1 c2=2 c1=3 c2=4 array content in hex: 31 32 33 34
Comments
Post a Comment