带结构指针的列表

时间:2016-07-04 20:21:44

标签: c

我有以下代码,但结果的所有组件的结果都为null:

#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;
}

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

1 个答案:

答案 0 :(得分:1)

您应该添加错误检查并且不建议使用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;
}