Saturday, 31 August 2013

2D dynamic allocation in C error when incrementing the pointer

2D dynamic allocation in C error when incrementing the pointer

I wanted to allocate a string array dynamically , the program is supposed
to ask the user for characters and collect them in the first string in the
array till letter 'q' is entered then the program starts adding the
characters to the second line and so on.
When I print the characters memory location it seems like each character
takes two memory cells instead of one though I increment it only once.
Here is the source code to my program
#include <stdio.h>
void main(){
char** txt;
char* baseAddress;
txt = (char **)malloc(5*sizeof(char*));
*txt = (char *)malloc(20*sizeof(char));
baseAddress=*txt;
while(*(*txt)!='q'){
(*txt)++;
scanf("%c",(*txt));
printf("%p\r\n",(*txt));
}
*txt='\0';
printf("%p",baseAddress);
free(baseAddress);
free(txt);
}
the output is like this
>j
>0x9e12021
>0x9e12022
>s
>0x9e12023
>0x9e12024
>
I think there may be something wrong with the pointers. How do I go about
accomplishing this? and sorry for the bad english

No comments:

Post a Comment