jcl@lingua.cltr.uq.OZ.AU (Jean-Claude Lacherez) (01/09/91)
Thanks to all those who replied to my question concerning dynamic dimensioning of arrays. Unfortunately the problem is not solved: 1/ First there was a confusing typo in my sample code, as follows: int maxrows, maxcols; char **array; maxrows = ...whatever... maxcols = ...whatever... array = (char **) malloc(maxcols * sizeof(char *)); for(x=0; x < maxrows; x++) ^^^^^^^ ^ | <This was meant to be maxcols> array[x] = (char *) malloc(maxrows); Sorry about that. This is not what I have in my original code and this is not the source of my problem. 2/ A couple of people pointed out that far pointers wrap at 64k, and suggested that I use huge pointers (at the cost of efficiency). However, the test program below which dimensions a really tiny array should not cause wrapping, and still it does not work. #include <stdio.h> #define NB_OF_ROWS 5 #define ROW_LENGTH 4 char *string[] = {"123", "456", "789", "ABC", "DEF"}; main() { char **array; int x, y; array = (char **) malloc(NB_OF_ROWS * sizeof(char *)); if (array == NULL){ puts("Fail 1"); exit(0); } else puts("ok "); for(x=0; x < NB_OF_ROWS; x++) { printf("Making row No %d\n", x); array[x] = (char *) malloc(ROW_LENGTH ); if (array[x] == NULL) { puts("Fail 2"); exit(0); } strcpy(array[x], string[x]); printf("array[%d] as string: %s\n", x, array[x]); printf("By characters: "); for(y=0; y < ROW_LENGTH; y++) printf("%c ",array[x][y]); putchar('\n'); } strcpy(array[0],"abc"); strcpy(array[1],"def"); strcpy(array[2],"hij"); strcpy(array[3],"klm"); strcpy(array[4],"nop"); printf ("\nNew values:\nas strings:"); for(x=0; x<NB_OF_ROWS; x++) printf("%s ",array[x]); printf("\nas chars:"); for(x=0; x<NB_OF_ROWS; x++) for(y=0; y < ROW_LENGTH; y++) printf("%c ",array[x][y]); } So there it is. Try it: it works on Unix, it works in Turbo C with the small memory model, it does not work with the large or with the huge models. Jean-Claude Lacherez Department of French University of Queensland QLD, 4072 AUSTRALIA jcl@lingua.cltr.uq.oz.au
emigh@ncsugn.ncsu.edu (Ted H. Emigh) (01/11/91)
In article <1991Jan9.012509.22427@lingua.cltr.uq.OZ.AU> jcl@lingua.cltr.uq.OZ.AU (Jean-Claude Lacherez) writes: >Thanks to all those who replied to my question concerning dynamic >dimensioning of arrays. Unfortunately the problem is not solved: The copy of his program follows: > #include <stdio.h> > > #define NB_OF_ROWS 5 > #define ROW_LENGTH 4 The problem is that he does not #include <stdlib.h>. For the small model, the pointer size is the same as the integer size. For the large model, the pointer size is larger than the integer size, but without the prototype it will stuff the result of the malloc into an integer. Moral: Turn on all the checking features of TC (or Zortech or MSC or ..). This would have been flagged immediately.