1

I have the following code but the result is null for all components of the structure:

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

i need to recover the structure values. Please any kind of help will be appreciate Thanks in advance for your help

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

1 Answers1

1

You should add error checking and casting of calloc values is discouraged, but the reason your code doesn't work is that you advance dbTransaction pointer in your loop, but never rewind it. The prints you're making are actually of elements 5-9 of the array while you fill elements 0-4.

See the corrected code:

#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;
}
Ishay Peled
  • 2,783
  • 1
  • 23
  • 37