gpt4 book ai didi

c - 带结构指针的列表

转载 作者:太空宇宙 更新时间:2023-11-04 03:29:24 25 4
gpt4 key购买 nike

我有以下代码,但结构的所有组件的结果均为空:

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

typedef struct _TransactionType
{
char field1[20];
char field2[20];
}TransactionType;

int main(int argc, char *argv[]) {
int i;
int numreg = 0;
char temp[12];
TransactionType *dbTransaction;

dbTransaction = (TransactionType*) calloc(10,sizeof(TransactionType));


for(i=0; i<5;i++)
{
memset(temp,0,sizeof(temp));
sprintf(temp,"%d",i);
strcpy(dbTransaction->field1, temp);
dbTransaction->field1[strlen(dbTransaction->field1)] = '\0';
strcpy(dbTransaction->field2, temp);
dbTransaction->field2[strlen(dbTransaction->field2)] = '\0';
numreg++;
dbTransaction++;
}

printf("reg = %d\n", numreg);

for (i=0; i<numreg;i++)
{
printf("dbTransaction->field1 = %s\n",(dbTransaction + i)->field1);
printf("dbTransaction->field2 = %s\n",(dbTransaction + i)->field2);

}


return 0;
}

我需要恢复结构值。请任何形式的帮助将不胜感激预先感谢您的帮助

最佳答案

您应该添加错误检查,并且不鼓励对 calloc 值进行强制转换,但是您的代码不起作用的原因是您在循环中推进了 dbTransaction 指针,但是永远不要倒带。当您填充元素 0-4 时,您正在打印的实际上是数组的元素 5-9。

查看修改后的代码:

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

typedef struct _TransactionType
{
char field1[20];
char field2[20];
}TransactionType;

int main(int argc, char *argv[]) {
int i;
int numreg = 0;
char temp[12];
TransactionType *dbTransaction;
TransactionType *dbTransactionRoot;

dbTransaction = (TransactionType*) calloc(10,sizeof(TransactionType));
dbTransactionRoot = dbTransaction;


for(i=0; i<5;i++)
{
memset(temp,0,sizeof(temp));
sprintf(temp,"%d",i);
strcpy(dbTransaction->field1, temp);
dbTransaction->field1[strlen(dbTransaction->field1)] = '\0';
strcpy(dbTransaction->field2, temp);
dbTransaction->field2[strlen(dbTransaction->field2)] = '\0';
numreg++;
dbTransaction++;
}

printf("reg = %d\n", numreg);

for (i=0; i<numreg;i++)
{
printf("dbTransaction->field1 = %s\n",(dbTransactionRoot + i)->field1);
printf("dbTransaction->field2 = %s\n",(dbTransactionRoot + i)->field2);

}


return 0;
}

关于c - 带结构指针的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38191742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com