我有一个程序(我们称它为pr),我不能理解为什么当一切似乎都正常的时候,突然我得到了一个错误。在终端中,我键入:
./pr 2011-11-01/03:20我想把日期和时间存储在两个数组中。数组aa == "2011-11-01“中的日期和bb ==中的时间"03:20”并在末尾打印它们。所以,我写了下面的代码:
编辑:使用下面的malloc()编辑新代码:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main (int argc, char *argv[]) {
int j=0, i=0;
char *aa = malloc(10*sizeof(char));
char *bb = malloc(5*sizeof(char));
while ( j!=10 ) {
aa[j] = *(argv[1]+j);
j++;
}
j++;
while ( *(argv[1]+j) != '\0' ) {
bb[j-11] = *(argv[6]+j++);
}
printf("%s and %s", aa, bb);
}但是上面的输出是:2011-11-01Y and 03:20,其中Y是一个随机字符...
编辑结束...
下面是一个旧版本:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main (int argc, char *argv[])
{
char *aa, *bb; int j=0, i=0;
while ( *(argv[1]+j) != '/' )
{
aa[j] = *(argv[6]+j++);
}
j++;
while ( *(argv[1]+j) != '\0' )
{
bb[i++] = *(argv[1]+j++);
}
printf("%s %s", aa, bb);
}由于某种原因,上面的代码不能工作,但是当我写到:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main (int argc, char *argv[])
{
char *aa; int j=0;
while ( *(argv[1]+j) != '/' )
{
aa[j] = *(argv[1]+j++);
}
printf("%s", aa);
}或
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main (int argc, char *argv[])
{
char *bb; int j, i=0;
j=11; printf("%d", j);
while ( *(argv[1]+j) != '\0' )
{
bb[i++] = *(argv[1]+j++);
}
printf("%s", bb);
}它工作得很好!有人知道为什么会这样吗?
发布于 2014-03-17 07:49:16
你应该这样做
char *aa = malloc(11*sizeof(char));为了说明\0字符,并且在第一次循环之后,您应该这样写
aa[j] = '\0'基本上,您不会以\0结束aa字符串,因此printf不会在最后一个字符处停止,因此之后会有一个随机的字符串。
https://stackoverflow.com/questions/22441616
复制相似问题