For simplicity, I am just going to put everything into a single source file.
Code:
#include <stdio.h>
#include <stdlib.h>
struct pointsscored
{
char name[20];
int goals;
int behinds;
};
void print_data(void *ptr);
int main()
{
struct pointsscored *ptr;
int i, numofplayers = 3;
ptr = (struct pointsscored*) malloc(numofplayers * sizeof(struct pointsscored));
for(i=0;i<numofplayers;++i)
{
printf("Enter name, goals and behinds of player %d (use the space bar to seperate)\n", i+1);
scanf(" %s%d%d", &(ptr+i)->name, &(ptr+i)->goals, &(ptr+i)->behinds);
}
for(i=0;i<numofplayers;++i)
{
print_data(ptr);
}
//system("pause");
return 0;
}
void print_data(void *ptr)
{
printf("%s" , ((char)ptr->name));
}
Then compile with full warnings:
Code:
main.c||In function 'main':|
main.c|23|warning: format '%s' expects type 'char *', but argument 2 has type 'char (*)[20]'|
main.c||In function 'print_data':|
main.c|37|warning: dereferencing 'void *' pointer|
main.c|37|error: request for member 'name' in something not a structure or union|
||=== Build finished: 1 errors, 2 warnings ===|
I would suggest not working with void pointers in your function parameters as a beginner. Just make your parameter an explicit pointer to the struct type.
Some other notes:
- Check that malloc succeeds before attempting to use that memory.
- When using "scanf" to read a string, you shouldn't include the '&', as an array name by itself acts as a pointer to its first element.
- You don't need to cast malloc: FAQ > Casting malloc - Cprogramming.com
- Whatever memory you allocate, you should free.
Here is a simplified example to illustrate the process:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct struct_str
{
char s[20];
};
void print_str(struct struct_str *test);
int main(void)
{
struct struct_str *stest;
stest = malloc(sizeof(*stest)); /* error checking omitted */
strcpy(stest->s, "This is a test.");
print_str(stest);
free(stest);
return 0;
}
void print_str(struct struct_str *test)
{
printf("%s\n", test->s);
}