【发布时间】:2019-09-27 20:45:39
【问题描述】:
我已经准备好我的令牌,但我希望它们存储在一个数组中。
我尝试过创建一个数组并将令牌存储在其中,但是当我在我的情况下打印出数组时str[0]。
它只打印一个字符而不是整个令牌。
int i=0, j=0, t=0;
char *ptr = argv[1];
char *str;
str =(char*) malloc(10 * sizeof(int));
while (ptr[i] != '\0')
{
if (ptr[j] != ';')
{
printf("%c", ptr[j]);
str[t] = ptr[j];
j++;
}else
{
if (ptr[j] == ';')
{
j++;
str[t] = ptr[j];
printf("%c\n", ptr[j]);
}
}
i++;
t++;
}
printf("\n%c",str[1]);
我在代码上运行了这个
./check "true and false; 1 + 2"
它给我的输出是这样的
true and false
1 + 2
r
我的预期输出应该是1 + 2
因为我试图将整个令牌存储在数组的一个索引中
str[0]: true and false
str[1]: 1 + 2
【问题讨论】:
-
if (ptr[j] != ';') {...} else { if (ptr[j] == ';') {... }}if (ptr[j] == ';')是多余的。见:Do I cast the result of malloc?(答案:否)“str[0]。它只打印一个字符”,你认为str[0]是什么类型? (提示:char)是什么让您认为它会存储更多? -
str是指向 char 的指针,str[0]因此是单个字符。你想要一个指向 char 的指针,然后你可以在每个元素中有多个 char。 -
除了很好的@DavidC.Rankin 评论以不转换
malloc()的结果,您必须检查str上的内存分配是否成功。 -
第二个如果
if (ptr[j] == ';' )没用。
标签: c malloc command-line-arguments