Hi there,
within an extensive code that I am developing I obtained a very strange behavior from the code itself, and I cannot figure out what it it that is not done correctly.
Specifically (code reported down here), I allocate certain arrays (2d and 1d) dynamically with standard dynamic allocation using malloc, and right after I assign them with the corresponding values.
The problem here comes from the first assignment of the 2D arrat "vars2[][]" through the 1D array rh_vals[] assigned elsewhere. With the first assignment within a "while loop" I verify the correctness of it by printing the "vars2[][]" and all is right, however, once I exit the while loop and I printf again "vars2[][]", here it is when I do not get the same array.
I hope someone can help although the sample code may seem large
best
CFD
Code:int i,j,k; int *dims; int *vardims; static char varname[NC_MAX_NAME+1]; const char **varnames2; //array of pointers to chars float *rh_vals; //vector float **vars2; //matrix int lonlength, latlength; //constants lonlength = 64; latlength = 512; nvars = 126; // Dynamic allocation of the arrays to pointers char **varnames and float **vars; // This line only allocates the number of entries but NOT the length of the entries: varnames2 = (const char**) malloc(1* sizeof(char)); varnames2[0] = (const char*) malloc( 12 * sizeof(char)); rh_vals = (float*) malloc( latlength*lonlength * sizeof(float)); vars2 = (float**) malloc(1* sizeof(float)); vars2[0] = (float*) malloc( latlength*lonlength * sizeof(float)); strncpy(varnames2[0], "T", 1); //WHILE LOOP starts HERE n = 0; while(n < nvars){ rh_val[n] = dumb_function(rh_val); //This function to find rh_vals isn't reported varname = dumb_function(varname); //This function to assign varname isn't reported strncpy(varnames2[n], varname, sizeof(varname)); if( strncmp(varnames2[n],"T",1) == 1){ k=0; for(i=0; i<lonlength; i++){ for(j=0; j<latlength; j++){ vars2[0][k] = rh_vals[k]; //FIRST PRINT TO CHECK VARS2 printf("k=%d rhvals[%d]: %f\n",k, k,vars2[0][k]); k++; }//end for j }//end for i }end if n++; }//END OF WHILE LOOP HERE. //ERROR HERE!!!! for(k=0; k<=latlength*lonlength; k++){ if(vars2[0][k] != 0.0) //SECOND PRINT TO CHECK VARS2 printf("k=%d rhvals[%d]: %f\n",k, k,vars2[0][k]); } //FREE DYN MEMORY: free(vars2); free(rh_vals); free(varnames2);



LinkBack URL
About LinkBacks



