假設:struct foo_t { int X,Y,Z; }
。某些函數需要一個數組struct foo_t
併爲其設置一些值;是這樣的:複製結構問題
void foo(struct foo_t *f, size_t limit, size_t *result_length)
{
int i = 0;
struct foo_t a;
a.X = 5;
//...
struct foo_t b;
b.X = 10;
// ...
struct foo_t c;
c.X = 4;
//...
f[i++] = a;
f[i++] = b;
f[i++] = c;
*result_length = i;
}
然後:
struct foo_t buf[12];
struct foo_t positive[12];
struct foo_t negative[12];
size_t len;
foo(buf, sizeof(buf)/sizeof(buf[0]), &len);
int c,positive_len,negative_len;
for(c = positive_len = negative_len = 0; c < len; c++)
{
if(buf[c].X < 8)
positive[positive_len++] = buf[c];
else
negative[negative_len++] = buf[c];
}
最後:
puts("POSITIVE:");
int i;
for(i = 0; i < positive_len; i++)
printf("%d\n", positive[i].X);
puts("NEGATIVE:");
for(i = 0; i < negative_len; i++)
printf("%d\n", nagative[i].X);
的問題如下:而不是越來越"POSITIVE:\n4\n5"
,"NEGATIVE:10"
我越來越5 and 5
和10
不打印。換句話說,只有最後一個值被設置。這是爲什麼發生?我大大減少了我的代碼,試圖在這裏獲得一些幫助,因爲真正的功能大約有300行代碼,包括數據庫管理等等。如果真的需要,我會在這裏發佈。前使用=操作符,我會用memcpy()
做結構的副本,我正/負陣列。
難道當你使用'memcpy'前工作的呢? – Xymostech
我不清楚你得到的輸出。它是'積極的:5 \ nNEGATIVE:5'? – philipvr
@Xymostech: – Jack