C: Globally define multidimensional char array -
what have is: read x strings s_1 ... s_x of defined max. length l=1000000 , store them. variable x given input , representation should globally defined.
how want is:
globally define pointer pointer char:
char** s;
locally, after reading x input, allocate space x pointers char:
s = (char**) malloc(sizeof(char*)*x);
locally allocating space each single string s_i , reading string allocated space:
while(i<x){ s[i] = (char*) malloc(sizeof(char)*1000000); scanf("%s",s[i]); i++; }
when try access
s[0][0]
it gives memory access error. ideas? thanks!
edit:
i printed array , worked fine problem indeed in accessing code. here is: can see what's problem? because can't...
makebinary(){ printf("inside makebinary()\n"); s_b = malloc(sizeof(int)*1000000*x); length = malloc(sizeof(int)*x); int i; int j; for(i=0;i<x;i++){ for(j=0;j<1000000;j++){ printf("1\n"); if(s[i][j]=='\0'){ printf("2\n"); length[i] = j; break; }else{ s_b[i][j] = s[i][j]-96; printf("3\n"); } } } }
it prints '1' crashes. know code far optimal solve problem first. thanks!
there lot of things going on:
changed strange casting malloc thing works icky.
shouldn't use sprintf copy memory... wouldn't allocate max.
can alloc correct amount, strlen()+1
... make sure 0 pad end... like:
int t = 100; char * buffer = malloc(sizeof(char*)*t); s = &buffer; for( int = 0; i<10 ; i++){ char * somestring = __file__; size_t len = strlen(somestring); s[i] = (char*) malloc(len+1); s[i][len] = 0; memcpy(s[i], somestring,len); }
Comments
Post a Comment