无法将参数存储为数组并在 C 中打印它们

标签 c arrays command arguments storage

我有这个程序(让我们称之为 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);
}

效果很好!有谁知道为什么会发生这种情况吗?

最佳答案

你应该这样做

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

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

aa[j] = '\0'

基本上,您不会以\0 结尾 aa 字符串,因此 printf 不会停止 在最后一个字符处,因此之后您会得到一个随机字符。

关于无法将参数存储为数组并在 C 中打印它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22441616/

相关文章:

permissions - 如何对特定用户或 channel 隐藏斜线命令 Discord.js v13

linux - ps h -fwC 有什么作用?

c - 访问超出报告容量的 block 设备数据

c++ - 使用 memcmp、memcpy 优化子例程

c++ - 无法使用 cuda 进入 __global__ 函数

python - 根据端点递归划分列表

连接的udp多播需要在发送方绑定(bind)

python - numpy 数组 : efficient way to compute argmax within a fixed window at a set of rows and columns given as input

python - 使用 lambda 进行 numpy 元素转换?

c++ - 'char' 之前的预期不合格 ID