0
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?

2
  • Why not std::vector<Student> instead of raw arrays? Commented Jun 23, 2021 at 17:29
  • i need via old tech. :( I am still not understand how am I supposed to print it out. Commented Jun 23, 2021 at 17:30

1 Answer 1

2
  • 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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.