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
*(*txt)has not been set yet). You may want to fix that as well as the other errors.main()isint— in standard C and in Microsoft C. Contrary to anything you see in text books,void main()is not an acceptable declaration formain()— though the Microsoft C compiler may not actually complain about it. And in MS code, you needreturn 0;or something at the end ofmain()because only C99 and later allows you to omit that return (a bug in the standard, IMNSHO, but it's far too late to worry about that), and MS only supports C89 which did not have that special dispensation formain().void main()from? 2. Don't cast the return frommalloc(). 3. Don't usesizeof(char), it's always 1. 4. Don't use so many parentheses, just learn your operator precedence, it doesn't make things clearer to pepper your code with them like this. 5. As WhozCraig said, you're accessing**txtbefore you've written to it, which is bad. 6. Don't use\r\nwhen printing tostdoutin normal text mode in C, it's just\n. 7. Always check whatmalloc()is actually returning, you may not get your memory.