Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array over written with last value assigned?

I have a pointer to pointer array. I am assigning each row in the while loop below and the printf inside the while loop shows each is assigned my id number 1-20.
After, out side of the while loop I iterate through the array and every element is written with id 20?
Any help is greatly appreciated. (FYI- I am using the Template2doc library and example1.c, at the bottom here- http://www.algonet.se/~thunberg/template2doc/c_version/docs/index.htm)

Below code only shows problem area, I took out the rest.

    char **tableData[500]={NULL};         
    char *myData[500][2]; 


while(rc == SQLITE_ROW){
    tableData[r] = myData[r];
    printf(*tableData[r]); <-- Displays id 1-20 fine
    r=r+1;
}//end while 

tableData[r+1] = NULL;//null terminated array

for (a=0; a<r; a++){
    printf("\n");
    printf(*tableData[a]);  <--Displays 20 elements all of id 20?
}


outputFile=insertTableData(outputFile, dataMarker, fieldMarker, tableData);
like image 432
T.T.T. Avatar asked Nov 27 '25 22:11

T.T.T.


2 Answers

You should create something that actually compiles and reproduces the problem. Not only will it help people help you, but in doing so you may very well find the problem yourself.

In your code excerpts we have no idea:

  • What rc is, how its value is set, or how its value is ever going to change and therefore terminate the loop
  • What the initial value of r is
  • What the actual contents of myData are

I created this code based on what you posted, which produces the same output from both loops. So either I've missed something in what you did post, or you left something important out.

int main( int argc, char** argv ) {

#define STRING  char *

STRING  dummy = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()";

STRING *tableData[500]={0};         
STRING myData[500][2];

int r=0;

while(r < 20){
        myData[r][0] = dummy+2*r;
        myData[r][1] = dummy+r;
        tableData[r] = myData[r];
        printf(*tableData[r]);
        printf("\n");
        r=r+1;
}//end while 

int a;

for (a=0; a<r; a++){
        printf(*tableData[a]);
        printf("\n");
}


}
like image 183
Dave Costa Avatar answered Nov 30 '25 11:11

Dave Costa


As pointed out, you are assigning Null at r+2 position. And are you in any way modifying tableData or myData in between the while and for loop?

like image 28
sachin Avatar answered Nov 30 '25 11:11

sachin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!