-3

以下代码将打印存储在每个Foo结构上的值。我遇到的问题是在给定 的值的情况下计算从哪里开始i,应该从哪里开始,它可能会有所不同。中的项目也可能有所不同。偏移量可以从 0 到分配的值的总量。在这种特殊情况下,它应该输出:joffsetFoooffset = 6

Bar: 0 - Foo: 6
Bar: 0 - Foo: 7
Bar: 0 - Foo: 8
Bar: 0 - Foo: 9

Bar: 1 - Foo: 0
Bar: 1 - Foo: 1
Bar: 1 - Foo: 2
Bar: 1 - Foo: 3
Bar: 1 - Foo: 4
...

但现在它输出:

Bar: 1 - Foo: 1
Bar: 1 - Foo: 2
Bar: 1 - Foo: 3
Bar: 1 - Foo: 4

Bar: 2 - Foo: 2
Bar: 2 - Foo: 3
Bar: 2 - Foo: 4

Bar: 3 - Foo: 3
Bar: 3 - Foo: 4
....

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int val;
} Foo;

typedef struct {
    int size;
    Foo *foo;
} Bar;

#define MAX 10
int main () {
    Bar bar[MAX];
    int i, j;
    int arr[10]={10,5,5,5,5,5,5,5,5,5};

    for(i = 0; i < MAX; i++) {
        bar[i].size = arr[i];
        bar[i].foo = malloc (sizeof (Foo) * bar[i].size);
        for(j = 0; j < bar[i].size; j++) {
            bar[i].foo[j].val = j;
        }
    }

    int offset = 6;
    int init = offset / 5;
    for (i = init; i < MAX; i++) {
        for (j = i % 5; j < bar[i].size; j++) {
            printf("Bar: %d - Foo: %d\n", i,  bar[i].foo[j].val); 
        }
        printf("\n");
    }

    return 0;
}
4

1 回答 1

0

你确定这是对的:

int init = offset / 5;

我认为这也不对:

for (j = i % 5; j < bar[i].size; j++) {

如果我正确理解问题设置,则每个“桶”(Foo对象)中的元素数量可能会有所不同,并且在计算起点时应考虑到有多少,然后从起点开始计数,直到您有打印了十个项目。这只需要一个循环。

于 2013-04-16T20:04:12.303 回答