Dying Pb
Dying Pb

Reputation: 25

C++ How to make Struct Input/Print via Pointers

struct Student
{
    char* name;
    int balls;
};

void inputdata(Student **s, int *n)
{
    int nn;
    printf("%s\n", "Input amount of students");
    scanf("%i", &nn);
    Student* a = new Student[nn];
    for (int i = 0; i < nn; ++i)
    {
        scanf("%s", &a[i].name);
        scanf("%i", &a[i].balls);
    }
    n = &nn;
    s = &a;
}
void print(Student **s, int n)
{
    for (int i = 0; i < n; ++i)
    {
        printf("%s %i\n", s[i]->name, s[i]->balls);
    }
}

int main(int argc, char const *argv[])
{
    Student** s;
    int *n;
    inputdata(s, n);
    print(s, *n);
    return 0;
}

So how am I supposed to input data and print data on console screen. I kinda input data, ok, unable to print it on my screen. Program ends. What am I supposed to fix here?

Upvotes: 0

Views: 45

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

  • You should pass pointers to what should be modified in callee functions.
  • Callee functions should dereference pointers passed to modify what should be modified.
  • You have to allocate for strings before reading.
  • It is inconsistent that an array of Student in the function inputdata but an array of Student* is required in the function print.
  • You should limit the maximum length to read to the number of elements in the buffer minus one to prevent buffer overrun when you use %s. The "minus one" is for terminating null-character.

Fixed code:

#include <cstdio>

struct Student
{
    char* name;
    int balls;
};

void inputdata(Student **s, int *n)
{
    int nn;
    printf("%s\n", "Input amount of students");
    scanf("%i", &nn);
    Student* a = new Student[nn];
    for (int i = 0; i < nn; ++i)
    {
        a[i].name = new char[4096];
        scanf("%4095s", a[i].name);
        scanf("%i", &a[i].balls);
    }
    *n = nn;
    *s = a;
}
void print(Student *s, int n)
{
    for (int i = 0; i < n; ++i)
    {
        printf("%s %i\n", s[i].name, s[i].balls);
    }
}

int main(int argc, char const *argv[])
{
    Student* s;
    int n;
    inputdata(&s, &n);
    print(s, n);
    return 0;
}

Upvotes: 2

Related Questions