c - 转储数组的内存内容

标签 c arrays

我的主要问题与 printf() 的使用和格式说明符有关。我有一个包含 100 个元素的数组,其中包含整数,其中大多数当前初始化为零。我想将内容以 10x10 block 格式转储到屏幕,如下所示:

       0     1     2     3     4     5 ...
0  +0000 +0000 +0000 +0000 +0000 +0000
1  +0000 +0000 ...
2  ...
3
...

使用我当前的代码,我的格式有点不对 -

    0       1       2       3       4       5       6       7       8       9    
    +1103   +4309   +1234   +0000   +0000   +0000   +0000   +0000   +0000   +0000
0   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000
1   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000
2   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000
3   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000
4   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000
5   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000
6   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000
7   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000
8   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000   +0000
9

当前(相关)代码:

void dump (int *dumpMemory, int SIZE) {
    int i = 0;
    for (i; i < 10; ++i) {                          // Output 1-10 at top row of dump
        printf("\t%d", i);
    }
    puts("");
    for (i = 0; i < SIZE; i++) {
        printf("\t%+05d", dumpMemory[i]);

        if ((i % 10) == 9) {
            printf("\n%d", (i / 10));
        }
    }
    puts("");
}

左侧索引已向下移动一个点,因此在打印到屏幕时无法正确表示其位置。

最佳答案

这主要是在正确的位置打印内容的问题。标题行不错。当 i % 10 == 0; 时,您需要在打印条目之前打印行前缀;当 i % 10 == 9; 打印条目后,需要打印换行符;循环后,如果i % 10 != 0,则需要打印换行符来终止数字行。然后可以选择是否添加另一个以在转储后放置一个空行。

void dump(int *data, int size)
{
    for (int i = 0; i < 10; ++i)  // Output headings 0..9
        printf("\t%d", i);
    putchar('\n');

    for (int i = 0; i < size; i++)
    {
        if (i % 10 == 0)
            printf("%d", i / 10);   // Consider outputting i?
        printf("\t%+05d", data[i]);
        if (i % 10 == 9)
            putchar('\n');
    }
    if (size % 10 != 0)
        putchar('\n');  // Finish current/partial line
    putchar('\n');      // Optional blank line
}

关于c - 转储数组的内存内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42776144/

相关文章:

c - 我的 C 中的 decToBase 方法出现错误并返回

c - Swift:UnsafeMutablePointer.deallocate(capacity:) 与 free() 的互操作性

c - 数组中需要左值错误

C - 结构体指针数组,语法

javascript - 如果值有逗号,则循环并将对象字符串值转换为对象

c - Arduino 处理开放网络套接字

c - 什么时候在 GNU C 中使用分离线程?

c - 函数中的双指针取消引用

javascript - 如果 "Undefined",则执行此操作,否则,使用数组和 .each() 执行此操作

C - 为什么我的数组被覆盖了?