First, i'm new to C and trying to teach it to myself so be gentle. All i'm trying to do is malloc a block of memory so that i can store a few strings. These strings are to be pointed at by an array of pointers so that as i increment the pointer, i point to the next word. My question is how come the block of malloc'd memory appears to contain only the 1st char of each string i'm attempting to strcpy?
int nrows = 4;
int ncols = 5;
int k, row, col;
rowptr = malloc(nrows*sizeof(int *));
arrayptr = malloc(nrows*ncols*sizeof(int));
for (k = 0; k < nrows; k++)
rowptr[k] = arrayptr + (k * ncols);
for (row = 0; row < nrows; row++)
printf("\n%d %p %c", row, rowptr[row],*rowptr[row]);
if (row > 0)
printf(" %d",(rowptr[row] - rowptr[row-1]));
for (col = 0; col < ncols*nrows; col++)
printf("\n %x %c",arrayptr+col,*(arrayptr+col));
10 Months Ago
Related Article:Random Quiz Question Generator
is a C discussion thread by TheOnlyRoss that has 14 replies, was last updated 1 year ago and has been tagged with the keywords: quiz, random.
Your types are wrong. Your compiler should have warned you about that. If it didn't, increase your warnings level - that will save you a lot of pain in the future.
arrayptr and rowptr should have types char* and char** respectively. Since you made arrayptr and int-pointer, your second for loop will iterate int-by-int, not char-by-char. So it's skipping over characters because ints are bigger than chars.
As mentioned, you also need to change the type of rowptr to a char** instead of an int**, and change the allocateion to rowptr = (char**)malloc(nrows*sizeof(char*)); or rowptr = (char**)calloc(nrows, sizeof(char*));
Thanks everyone! Especially sepp2k! You were right and i was getting warnings, but i didn't understand what the issue was. I now have everything working as expected and order has been restored in the universe!