【问题标题】:Can't store arguments as arrays and print them in C不能将参数存储为数组并在 C 中打印它们
【发布时间】:2014-03-16 19:18:15
【问题描述】:

我有程序(我们称它为 pr),但我不明白会发生什么,当一切似乎都正确时突然出现错误。在终端中,我输入:

./pr 2011-11-01/03:20

我想将日期和时间存储到 2 个数组中。数组 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);
}

效果很好!有人知道为什么会这样吗?

【问题讨论】:

  • 在第一个中,您在循环外增加j
  • 您正在写入未初始化的指针(aa 和 bb)。在写入循环之前,您需要为它们分配存储空间。
  • aabb 不是数组。它们是指针。
  • 使用 malloc 为 aa 和 bb 分配内存。
  • 我在这段代码中统计了至少三个不同的 undefined behavior 调用,包括(但不限于)写入 aabb 而作为不确定指针, 和 mashing a sequence point 违反 a[j] = &lt;&lt;something&gt;&gt;j++;

标签: c arrays command arguments storage


【解决方案1】:

你应该这样做

char *aa = malloc(11*sizeof(char));

考虑到 \0 字符,在第一个循环之后你应该写

aa[j] = '\0'

基本上,您不会以 \0 结束 aa 字符串,因此 printf 不会停止 在最后一个字符,因此你有一个随机的。

【讨论】:

    猜你喜欢
    • 2020-04-13
    • 2019-09-05
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2021-07-15
    • 2022-10-12
    相关资源
    最近更新 更多