将指针从 main() 移动到第一个可执行函数
Moving pointer from main() to first executable function
有什么方法可以将在 main()
函数中初始化的指针移动到第一个可执行函数并使其在整个程序中都可以访问?
代码如下:
主函数,指针d
初始化位置:
void main(){
int x;
deque *d;
d=(deque*)malloc(sizeof(deque));
initDeque(d);
我想将指针移动到名为 initDeque()
的函数中
void initDeque(deque *d){ //Create new deque
d->front=NULL;
d->rear=NULL;
}
可以移动吗?
如果 "move the pointer" 你的意思是你想移动变量声明,那么你可以这样做,但它将成为一个只能在该函数内部访问的局部变量。显然不是你想要的。
您需要将其设为全局,这样可以从所有范围访问它。请注意,全局变量被认为是丑陋的,会增加出错的风险,并且通常会使代码不那么清晰。
使用全局指针,它看起来像这样:
deque *d;
void initDeque(void)
{
d = malloc(sizeof *d);
d->front = d->rear = NULL;
}
注意你shouldn't cast the return value of malloc()
in C.
还要注意 nobody 会有一个使用单个小写字母命名的全局变量。 方式很容易将其与局部变量混淆,因此您应该至少使名称更明显,例如像
deque *theDeque;
创建一个静态结构来存储您想要分享的所有内容。
创建一个函数来分配你的双端队列。我不知道 deque 的大小也许你可以把它放在堆栈而不是堆上。
static struct {
deque d*;
} _G;
void main(){
int x;
_G.d = deque_new();
}
deque *deque_new(void){
deque *d;
d = malloc(sizeof(deque));
d->front=NULL;
d->rear=NULL;
return d;
}
或与堆栈
static struct {
deque d;
} _G;
void main(){
int x;
deque_init(&_G.d);
}
deque *deque_init(deque *d){
memset(d, 0, sizeof(*deque));
return d;
}
有什么方法可以将在 main()
函数中初始化的指针移动到第一个可执行函数并使其在整个程序中都可以访问?
代码如下:
主函数,指针d
初始化位置:
void main(){
int x;
deque *d;
d=(deque*)malloc(sizeof(deque));
initDeque(d);
我想将指针移动到名为 initDeque()
void initDeque(deque *d){ //Create new deque
d->front=NULL;
d->rear=NULL;
}
可以移动吗?
如果 "move the pointer" 你的意思是你想移动变量声明,那么你可以这样做,但它将成为一个只能在该函数内部访问的局部变量。显然不是你想要的。
您需要将其设为全局,这样可以从所有范围访问它。请注意,全局变量被认为是丑陋的,会增加出错的风险,并且通常会使代码不那么清晰。
使用全局指针,它看起来像这样:
deque *d;
void initDeque(void)
{
d = malloc(sizeof *d);
d->front = d->rear = NULL;
}
注意你shouldn't cast the return value of malloc()
in C.
还要注意 nobody 会有一个使用单个小写字母命名的全局变量。 方式很容易将其与局部变量混淆,因此您应该至少使名称更明显,例如像
deque *theDeque;
创建一个静态结构来存储您想要分享的所有内容。 创建一个函数来分配你的双端队列。我不知道 deque 的大小也许你可以把它放在堆栈而不是堆上。
static struct {
deque d*;
} _G;
void main(){
int x;
_G.d = deque_new();
}
deque *deque_new(void){
deque *d;
d = malloc(sizeof(deque));
d->front=NULL;
d->rear=NULL;
return d;
}
或与堆栈
static struct {
deque d;
} _G;
void main(){
int x;
deque_init(&_G.d);
}
deque *deque_init(deque *d){
memset(d, 0, sizeof(*deque));
return d;
}