1

I am trying to make a global array of structs, however the way in which I thought I would go about this doesn't work. For the application I need requires it be be global however will not know the size until inside the main() function. My code is as follows:

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//
struct player {
    char letter;
};

struct player *players;

int main(int argc, char** argv){
    check _variables();
    int *inpBuff;
    inpBuff = convert_input(argv[1], argv[2]);
    int numPlayers = inpBuff[0];
    players =  malloc(numPlayers*sizeof(player));
    return 1;
}

I receive the error: error: 'player' undeclared (first use in this function) players = malloc(numPlayers*sizeof(player));

5
  • 1
    The struct is called struct player. Commented Sep 13, 2018 at 5:41
  • @immibis I'm new to C can you please let me know what does char** argv works for? why two ** after char? Commented Sep 13, 2018 at 5:49
  • 1
    @ZeeshanAdil Here is a link for better understanding: geeksforgeeks.org/command-line-arguments-in-c-cpp Commented Sep 13, 2018 at 6:06
  • @user10334659 Thanks for sharing, will have a look! :) Commented Sep 13, 2018 at 6:09
  • 1 is not a portable exit status. On at least one system it means "success", but on Unix/Windows it is an error code. The portable return values of main are 0 or EXIT_SUCCESS for success and EXIT_FAILURE for failure. Commented Sep 13, 2018 at 6:12

1 Answer 1

2

SOURCE OF ERROR--> You are using player instead of players in malloc which is incorrect. Player is the name of struct and you need the pointers name in malloc.

First --> You need to correct your malloc statement --> use players = malloc(numPlayers*(sizeof(*players));

Second --> When return type of main() function is int then your return statement seems to be missing.

Sign up to request clarification or add additional context in comments.

2 Comments

The first point you made didn't stop me from receiving the error: error: 'player' undeclared (first use in this function) players = malloc(numPlayers*sizeof(player)); As for you second point this is because I only posted a snippet of the code and forgot the return.
return is optional in main. Since C99, running off the end of main automatically returns 0.

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.