我想动态分配一个字符串数组,该程序应该询问用户字符,并将它们收集在数组的第一个字符串中,直到输入字母“ q”,然后程序开始将字符添加到第二行,依此类推。 。
当我打印字符存储位置时,尽管每个字符只增加一次,但似乎每个字符占用两个存储单元而不是一个。
这是我程序的源代码
#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);
}
输出是这样的
>j
>0x9e12021
>0x9e12022
>s
>0x9e12023
>0x9e12024
>
我认为指针可能有问题。我该如何完成这项工作?对不起,英语不好
您编写的代码有什么用途:
+----------------------------------------------+
| +--------------------------------------+ |
| txt|*txt |*txt+1 |*txt+2 |*txt+3 |*txt+4 | |
| +--------------------------------------+ |
| ^ ^ no memory alloc ^ |
| | |_______not used_______| |
| +----+ |
|*txt |____| <------------------------------+---you never give a value here,
| +1 |____| <--j |
| +2 |____| <-- '\n' |
| +3 |____| <--s |
| +4 |____| <-- '\n' |
| . . |
| . . |
| . ____ |
| +19 |____| |
+----------------------------------------------+
因此,您需要:
'\n'
建议:
在你的第一个字符串中
使用txt[0]
代替*txt
,使用txt[0][i] and i++
代替**txt and (*txt)++
。
希望能帮上忙。:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句