Search code examples
cpointersstructretention

Struct not retaining data when passed as a pointer


I've defined a header file with a struct and function prototypes that take a pointer to a struct as a parameter. The code compilation goes fine except that struct instantiated in the main do not seem to retain numerical data.

This is the header file:

#ifndef _GETDATA
#define _GETDATA
#include <stdio.h>
struct PERSONDATA{
    char name[20];
    double age,mass;
};
typedef struct PERSONDATA person;
extern void getData(person *);
extern void getName(char *,int);
#endif

This is the getData.c file:

#include <stdio.h>
#include "GETDATA.h"
void getData(person *ptr)
{
    printf("Enter name: ");
    getName(ptr->name,sizeof(ptr->name));
    printf("enter age: ");
    scanf("%f",&(ptr->age));
    printf("enter mass: ");
    scanf("%f",&(ptr->mass));
}

and this is the getName.c file:

#include <stdio.h>
#include "GETDATA.h"
void getName(char *ptrName, int varSize)
{
    int i=0;
    do
    {
        *(ptrName++) = getchar();
        ++i;
        if(i==varSize) printf("array full, EXITING!\n");
    }while(*(ptrName-1)!='\n' && i<varSize);
    *(ptrName-1) = '\0';
}

The main function is as follows:

#include <stdio.h>
#include "GETDATA.h"
int main(int argc, char **argv)
{
    person human1;
    printf("hello, world!\n\n");
    getData(&human1);
    printf("\nData entered: \n");
    printf("\tname = %s\n",human1.name);
    printf("\tMass = %f\n",&(human1.mass));
    printf("\tAge = %f\n",&(human1.age));
    return 0;
}

This is the console output when the code is run:

As you can see, the struct human1 do not seem to retain the numerical data but retains the string

What could be going wrong here?


Solution

  • Your values are doubles, not floats. You need to use %lf with scanf():

    printf("enter age: ");
    scanf("%lf",&(ptr->age));
    printf("enter mass: ");
    scanf("%lf",&(ptr->mass));
    

    Also, your prints are wrong. You are passing a pointer. It should be

    printf("\tMass = %f\n",human1.mass);
    printf("\tAge = %f\n",human1.age);