C программирование с аргументом массивов типа "struct student" несовместимо с параметром типа "struct student *" error - PullRequest
0 голосов
/ 26 января 2020

Привет, я делаю эту программу для класса c, и я стараюсь изо всех сил пытаться приехать сюда, потому что я не могу go своему учителю или отделу репетиторства, поскольку они недоступны, когда Я не работаю.

У меня проблема с этими двумя функциями

void examination_seating_init(int rowNum, int columnNum, struct examination_seating* t)
{
    struct student* placeholder;
    for (int row = 0; row < columnNum; row++) {
        for (int col = 0; col < rowNum; col++) {
            *placeholder = t->seating[row][col];
            student_init_default(placeholder);
        }
    }
}

void examination_seating_to_string(struct examination_seating* t)
{
    char seatingchart = "The current seating: \n --------------------\n";
    struct student *temp;
    for (int row = 0; row < sizeof t->seating; row++) {
        for (int col = 0; col < sizeof t->seating[0]; col++) {
            if (col == sizeof t->seating[0] - 1) {
                *temp = t->seating[row][col];
                student_to_string(temp);
                seatingchart = ("%c %c \n", seatingchart, temp);
            }
            else {
                    *temp = t->seating[row][col];
                    student_to_string(temp);
                    seatingchart = ("%c %c ", seatingchart, temp);
            }

        }
    }
    printf("%c", seatingchart);
}

Обе они дают мне неинициализированную локальную переменную, используемую ошибку, я не уверен, что есть лучший способ чтобы делать то, что я пытаюсь сделать, или что конкретно я делаю неправильно, любая помощь была бы удивительной. Я включил сюда свою полную программу для справки.

Я также пробовал это

{
    for (int row = 0; row < columnNum; row++) {
        for (int col = 0; col < rowNum; col++) {
            student_init_default(t->seating[row][col]);
        }
    }
}

, но что дает мне аргумент типа "struct student" несовместим с параметром типа "struct student *" error


    #pragma warning(disable : 4996)

#include <stdio.h>
#include <string.h>

struct student {
    char last_name[30];
    char first_name[30];
};
struct examination_seating {
    struct student** seating;
};
void student_init_default(struct student* p)
{
    int i;
    for (i = 0; i < sizeof p; ++i) {
        p->first_name[i] = '###';
        p->last_name[i] = '###';
    }
}
void student_init(struct student* p, char* info)
{
    char* names;
    names = strtok(info, "/");
    while (names != NULL)
    {
        p = names;
        names = strtok(NULL, "/");
    }
}

void student_to_string(struct student* p)
{
    char initials = "";
    initials = ("%c.%c", p->first_name[0], p->last_name[0]);
    return initials;
}

void examination_seating_init(int rowNum, int columnNum, struct examination_seating* t)
{
    struct student* placeholder;
    for (int row = 0; row < columnNum; row++) {
        for (int col = 0; col < rowNum; col++) {
            *placeholder = t->seating[row][col];
            student_init_default(placeholder);
        }
    }
}

int assign_student_at(int row, int col, struct examination_seating* t, struct student* p)
{
    if (strcmp(t->seating[row][col].first_name, "###"))
    {
        t->seating[row][col] = *p;
    }
    else
    {
        return 0;
    }
}

int check_boundaries(int row, int col, struct examination_seating* t)
{
    if (sizeof t->seating > 0 | t->seating < row)
        if (sizeof t->seating[0] > 0 | t->seating[0] < col)
        {
            return 1;
        }
        else
        {
            return 0;

        }
}

void examination_seating_to_string(struct examination_seating* t)
{
    char seatingchart = "The current seating: \n --------------------\n";
    struct student *temp;
    for (int row = 0; row < sizeof t->seating; row++) {
        for (int col = 0; col < sizeof t->seating[0]; col++) {
            if (col == sizeof t->seating[0] - 1) {
                *temp = t->seating[row][col];
                student_to_string(temp);
                seatingchart = ("%c %c \n", seatingchart, temp);
            }
            else {
                    *temp = t->seating[row][col];
                    student_to_string(temp);
                    seatingchart = ("%c %c ", seatingchart, temp);
            }

        }
    }
    printf("%c", seatingchart);
}

void main() {
    struct examination_seating examination_seating;
    struct student temp_student;
    int row, col, rowNum, columnNum;
    char student_info[30];
    // Ask a user to enter a number of rows for a examination seating
    printf("Please enter a number of rows for a examination seating.");
    scanf("%d", &rowNum);
    // Ask a user to enter a number of columns for a examination seating
    printf("Please enter a number of columns for a examination seating.");
    scanf("%d", &columnNum);
    // examination_seating
    examination_seating_init(rowNum, columnNum, &examination_seating);
    printf("Please enter a student information or enter \"Q\" to quit.");
    /*** reading a student's information ***/
    scanf("%s", student_info);
    /* we will read line by line **/
    while (1 /* change this condition*/) {
        printf("\nA student information is read.");
        // printing information.
        printf("%s", student_info);
        // student
        student_init(&temp_student, student_info);
        // Ask a user to decide where to seat a student by asking
        // for row and column of a seat
        printf("Please enter a row number where the student wants to sit.");
        scanf("%d", &row);
        printf("Please enter a column number where the student wants to sit.");
        scanf("%d", &col);
        // Checking if the row number and column number are valid
        // (exist in the examination that we created.)
        if (check_boundaries(row, col, &examination_seating) == 0) {
            printf("\nrow or column number is not valid.");
            printf("A student %s %s is not assigned a seat.", temp_student.first_name, temp_student.last_name);
        }
        else {
            // Assigning a seat for a student
            if (assign_student_at(row, col, &examination_seating, &temp_student) == 1) {
                printf("\nThe seat at row %d and column %d is assigned to the student", row, col);
                student_to_string(&temp_student);
                examination_seating_to_string(&examination_seating);
            }
            else {
                printf("\nThe seat at row %d and column %d is taken.", row, col);
            }
        }
        // Read the next studentInfo
        printf("Please enter a student information or enter \"Q\" to quit.");
        /*** reading a student's information ***/
        scanf("%s", student_info);
    }
}

1 Ответ

0 голосов
/ 26 января 2020

Вы, похоже, неправильно понимаете, как работают указатели в c.
Я бы начал здесь: https://computer.howstuffworks.com/c20.htm это продолжается на нескольких страницах (нажмите далее).
Теперь чтобы решить проблему, вы должны выделить место, на которое вы указываете.
Смотрите здесь, как это сделать: https://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/
Также некоторая информация о строках в c: https://www.programiz.com/c-programming/c-strings
Я исправил проблемы, о которых вы спрашивали (и некоторые другие), однако в коде, вероятно, есть и другие проблемы.
Я рекомендую вам узнать больше о указатели, распределение и строки в c.
Для одного char не является строкой, и char * должен быть выделен. Если он размещен в функции и возвращен (как в student_to_string), вы должны разместить его динамически или вне функции (как я сделал).

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct student {
    char last_name[30];
    char first_name[30];
};
struct examination_seating {
    struct student** seating;
};
void student_init_default(struct student* p)
{
    strcpy(p->first_name, "###");
    strcpy(p->last_name, "###");
}
void student_init(struct student* p, char* info)
{
    int i=0;
    int j=0;
    char * current = p->first_name;
    while (info[i] != 0)
    {
        if (info[i] == '/')
        {
            current[j]=0;
            current = p->last_name;
            j=0;
        }
        else {
            current[j] = info[i];
            j++;
        }
        i++;
    }
    current[j]=0;
}

void student_to_string(struct student* p, char * initials)
{
    sprintf(initials, "%c.%c", p->first_name[0], p->last_name[0]);
}

void examination_seating_init(int rowNum, int columnNum, struct examination_seating* t)
{
    t->seating = malloc(rowNum * sizeof(struct student *)); 
    for (int row = 0; row < columnNum; row++) {
        t->seating[row] = malloc(columnNum* sizeof(struct student));
        for (int col = 0; col < rowNum; col++) {
            student_init_default(&(t->seating[row][col]));
        }
    }
}

int assign_student_at(int row, int col, struct examination_seating* t, struct student* p)
{
    if (!strcmp(t->seating[row][col].first_name, "###"))
    {
        strcpy(t->seating[row][col].first_name, p->first_name);
        strcpy(t->seating[row][col].last_name, p->last_name);
        return 1;
    }
    else
    {
        return 0;
    }
}

int check_boundaries(int row, int rowNum, int col, int colNum)
{
    if (row > 0 | row < rowNum)
        if (sizeof col > 0 | col < colNum)
        {
            return 1;
        }
        else
        {
            return 0;

        }
}

void examination_seating_to_string(struct examination_seating* t)
{
    char seatingchart[] = "The current seating: \n --------------------\n";
    struct student *temp;
    char initials[4];
    for (int row = 0; row < sizeof t->seating; row++) {
        for (int col = 0; col < sizeof t->seating[0]; col++) {
            if (col == sizeof t->seating[0] - 1) {
                student_to_string(&t->seating[row][col], initials);
                sprintf(seatingchart,"%s %s \n", seatingchart, initials);
            }
            else {
                    student_to_string(&t->seating[row][col], initials);
                    sprintf(seatingchart,"%s %s ", seatingchart, initials);
            }

        }
    }
    printf("%s", seatingchart);
}

void main() {
    struct examination_seating examination_seating;
    struct student temp_student;
    int row, col, rowNum, columnNum;
    char student_info[30];
    char initials[4];
    // Ask a user to enter a number of rows for a examination seating
    printf("Please enter a number of rows for a examination seating.");
    scanf("%d", &rowNum);
    // Ask a user to enter a number of columns for a examination seating
    printf("Please enter a number of columns for a examination seating.");
    scanf("%d", &columnNum);
    // examination_seating
    examination_seating_init(rowNum, columnNum, &examination_seating);
    printf("Please enter a student information or enter \"Q\" to quit.");
    /*** reading a student's information ***/
    scanf("%s", student_info);
    /* we will read line by line **/
    while (1 /* change this condition*/) {
        printf("\nA student information is read.");
        // printing information.
        printf("%s", student_info);
        // student
        student_init(&temp_student, student_info);
        // Ask a user to decide where to seat a student by asking
        // for row and column of a seat
        printf("Please enter a row number where the student wants to sit.");
        scanf("%d", &row);
        printf("Please enter a column number where the student wants to sit.");
        scanf("%d", &col);
        // Checking if the row number and column number are valid
        // (exist in the examination that we created.)
        if (check_boundaries(row, rowNum, col, columnNum) == 0) {
            printf("\nrow or column number is not valid.");
            printf("A student %s %s is not assigned a seat.", temp_student.first_name, temp_student.last_name);
        }
        else {
            // Assigning a seat for a student
            if (assign_student_at(row, col, &examination_seating, &temp_student) == 1) {
                printf("\nThe seat at row %d and column %d is assigned to the student", row, col);
                student_to_string(&temp_student, initials);
                examination_seating_to_string(&examination_seating);
            }
            else {
                printf("\nThe seat at row %d and column %d is taken.", row, col);
            }
        }
        // Read the next studentInfo
        printf("Please enter a student information or enter \"Q\" to quit.");
        /*** reading a student's information ***/
        scanf("%s", student_info);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...