繁体   English   中英

帮助函数中的指针指向动态分配的结构数组?

[英]Assistance with pointers in functions to a dynamically allocated array of structs?

我正在制作一个有关从系外行星收集元素的游戏。 如果我可以在一个函数中完成所有操作,而我将结构数组的指针传递给多个函数,则我没有问题。 因此,我不断收到错误消息,因为我不知道要放置每个函数的参数和参数的指针数。 特别是函数中的函数(称为missionMenu())是一个让人头疼的问题。 我可能也弄乱了函数earth()中的指针。任何帮助将不胜感激!

编辑:我需要帮助在missionMenu()函数中修复scanf,我认为上面提到的指针的滥用与它有关

#include <stdio.h>
#include <stdlib.h>
#define pause system("pause")
#define cls system("cls")
#define flush fflush(stdin)
#define SIZE 1000


main(){

    int count=0;

    ELEMENT* element[SIZE];
    earth(&count,element);

}//End main 

void earth(int *c,ELEMENT **element){

    int userMenuChoice = 0; 
    int i;
    int number;
    displayMenu(); 

    element[*c] = malloc(sizeof(ELEMENT));

    scanf("%i", &userMenuChoice); 

    switch (userMenuChoice) { 
            case 1: 

                missionMenu(element[*c],*c);

                break; 
            case 2: 
                for(i=0;i<*c;i++)
                    printf("\t%i\t%i\n", element[i]->hydrogen);
                break; 
            case 3: 

                break;
    }while(userMenuChoice != 4); 

}//end end

void missionMenu(ELEMENT *element, int c ){
    int missionChoice;
    cls;

    printf("Which planet would you like to escapade/exploit? \n\n"); 
    printf("1. Gliese 436 b \n");
    printf("2. Oxygen Planet\n"); 
    printf("3. 55 Cancri E\n"); 
    printf("4. Nitrogen \n"); 
    printf("Please input your choice (1-3): \n\n"); 

    missionChoice = 0; 
    scanf("%i", &missionChoice); 
    switch (missionChoice) { 
            case 1: 

                cls;
                printf("\n\n\nWelcome to Planet Gliece 436 b, a planet made of burning ice.\n");
                printf("The extreme gravity of this planet forces the water to stay in solid form,\neven though the temperature is over 570° fahrenheit.\n\n");
                pause;




                printf("\n\n\tHow much Hydrogen would you like to collect?");
                //scanf("%i",&collect);
                scanf("%[^\n]s", element->hydrogen); flush;
                printf("\n\ntHow much Oxygen would you like to collect?");
               // scanf("%i",&collect);
                scanf("%[^\n]s", element->oxygen); flush;
                c=c+1;
                break; 
            case 2: 

                break; 
            case 3: 

                break;
            case 4:

                break;
    }while(missionChoice != 5); 
}//end mission menu



ELEMENT** newElement() {
    ELEMENT** element;
    element = malloc(sizeof(ELEMENT));
    return element;
} //end newTeam

在您的main您尝试使用指向ELEMENT(您的数组)的指针来调用earth函数。 如果检查earth(...)的定义,则会看到它接受指向ELEMENT的指针的指针,这不是您要传递的指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM