您可能还想考虑“createPlayer”函数感觉好像它正在创建一个供应用程序使用的新播放器。仅当您需要在代码中使用它时才为结构分配内存,并在完成后丢弃内存,这是一种习惯且非常强大的做法。此外,这样做可以让您在运行代码时创建任意数量的“播放器”并随意使用它们。
下面是一篇文章,展示了如何使用动态内存分配(在程序执行时分配内存)来完成它。
让我们创建一个头文件 (.h) 来存放我们的定义
播放器.h:
/* this player.h header file is used by other parts of our program to access
* the player functionality definitions and interface
*/
/* the #ifndef / #define below protects against inadvertent syntax errors
* that may occur by double inclusion of the same file.
*/
#ifndef _PLAYER_H
#define _PLAYER_H
struct player {
char name[40];
int acceleration;
};
extern struct player * create_player(const char *name, int acceleration);
void delete_player(struct player *p);
const char * get_player_name(struct player *p);
void set_player_name(struct player *p, const char *name);
int get_player_accel(struct player *p);
void set_player_accel(struct player *p, int accel);
/* you can add other functions here and then define their implementation in player.c
shown below */
#endif /* _PLAYER_H */
让我们创建一个 player.c,其中包含 player.h 中定义的函数的实现
玩家.c:
/* include memory management functions */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "player.h" /* we created this above */
/* Define the structure */
定义管理结构分配的函数
/* create_player function allocates memory for a new player structure
* and returns the pointer to it upon succcess. It returns NULL on failure
*/
struct player * create_player(const char *name, int acceleration) {
struct player *new_player = malloc(sizeof(struct player));
/* malloc allocates memory for the sizeof the structure and returns
the pointer to it */
if ( !new_player ) {
/* typically we don't put error messages in production code
* it is handled elsewhere but verbosity
* is okay for learning, so we add an error message */
fprintf(stderr, "unable to allocate memory for a new player\n");
return NULL;
}
}
/* delete_player deallocates memory that was allocated in create_player
* only pass it the pointers that were created by create_player structure
*/
void delete_player(struct player *p) {
if (p)
free(p);
}
/* let's do some house keeping functions */
const char * get_player_name(struct player *p) {
if ( p )
return p->name;
else
return NULL;
}
void set_player_name(struct player *p, const char *name) {
if ( p ) {
strncpy(p->name, name, sizeof(p->name)); /* only 40 characters */
}
}
int get_player_accel(struct player *p) {
return p->acceleration;
}
void set_player_accel(struct player *p, int accel) {
if ( p )
p->acceleration = accel;
}
现在在您的代码的其他地方,您可以像这样使用上述函数:
main.c:
#include <stdio.h>
#include "player.h"
int main() {
struct player *player = create_player("john", 30);
if ( player ) {
printf("%s's acceleration is %d\n", player->name, player->acceleration);
}
}
使用您的 c 编译器用这两个 c 文件编译程序(如果您使用的是 C IDE,请将它们添加到您的项目中)。构建项目... .
如果您使用的是命令行,那么:
cc -o player_test player.c main.c
应该做的伎俩
注意
现在我在没有使用 ac 编译器的情况下写了这一切,所以我可能会遇到一些语法错误......请从中获得 C 的感觉,而不是从字面上使用它:) 以防出现愚蠢的错误。