### Thread: 2D Array Sorting Help

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
4
Rep Power
0

#### 2D Array Sorting Help

I am having some trouble getting the following loops to work correctly.

PHP Code:
```  for(x=1; x < i - 1; x++) {                  for(y= x + 1; y < i - 1; y++) {                          tempD1 = atol(dataArray[x][j]);             tempD2 = atol(dataArray[y][j]);                          printf("TempD1 : %ld \n TempD2 : %ld\n", tempD1, tempD2);                          if( tempD1 > tempD2 ) {                                  for(j=0; j < COLUMNS; j++ ) {                                          printf("%i", j);                                          char tempStr[MAX_STRING_LEN];                                          strcpy(tempStr, dataArray[x][j]);                                          printf("%s \n" , tempStr);                                          dataArray[x][j] = dataArray[y][j];                                          dataArray[y][j] = strdup(tempStr);                                      }             }                      }              }  ```
the tempD1 and tempD2 values are both 0 for all loops after the first. I assume this is due to my lack of understanding of the atol() function, but I also ran into this problem with the strtod() function as well. Any help would be greatly appreciated. Thanks a lot.
2. Show us how you declare dataArray and what it is initialised to.

> tempD1 = atol(dataArray[x][j]);
What is j at this point?

You also have a j loop later on as well.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
4
Rep Power
0
char *dataArray[ROWS][COLUMNS];

a file is read into this array.

j is the column number of the array that the array will be sorted numerically by. j = 6 at this point.
4. So to swap two pointers, you do
Code:
```char *temp = dataArray[x][j];
dataArray[x][j] = dataArray[y][j];
dataArray[y][j] = temp;```
5. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
4
Rep Power
0
wow so that worked, thank you very much.

any idea why i was receiving values of zero for tempD1 and tempD2 when I was swapping pointers the other way? I am new at this and trying to learn.
6. A couple of things.

1. You had a loop, where none was necessary.
> for(j=0; j < COLUMNS; j++ )

2.
strcpy(tempStr, dataArray[x][j]);
dataArray[x][j] = dataArray[y][j];
dataArray[y][j] = strdup(tempStr);

Copying strings would have worked (slowly), had you actually used 3 strcpy calls (ignoring the separate loop issue).

A final point, strdup() uses malloc to make a copy of a string.
At some point, you would need to call free() as well. This code is just a massive memory leak.
7. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2012
Posts
4
Rep Power
0
Thank you.