gpt4 book ai didi

c - 为什么 C 会给出此错误 ‘size’ undeclared(在此函数中首次使用)?

转载 作者:行者123 更新时间:2023-11-30 20:26:09 24 4
gpt4 key购买 nike

我是c编程的初学者。我可以编写自己的 malloc 函数,并将 main 方法代码放在其中之一。它给出以下错误。

test.c: In function ‘main’:

test.c:38:30: error: ‘size’ undeclared (first use in this function)

test.c:38:30: note: each undeclared identifier is reported only once for each function it appears in

代码

  /*An horrible dummy malloc*/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void *malloc(size_t size);



void *malloc(size_t size){
void *p;
p = sbrk(0);
//if sbrk dails , we return null
if(sbrk(size)==(void*)-1){
return NULL;
}
printf("wada\n");
return p;
}

typedef struct s_block *t_block;

struct s_block{
size_t size;
t_block next;
int free;
};


int main(){
malloc(50);
malloc(100);

t_block b;
b = sbrk(0);
sbrk(sizeof(struct s_block)+size);//Error line (code 1)
b->size = size; //Error Line
return 0;
}

最佳答案

在这一行:sbrk(sizeof(struct s_block)+size)中,您使用了一个未在任何地方定义的变量size。错误消息中清楚地说明了这一点。

顺便说一句,你应该给你的函数命名,而不是malloc

关于c - 为什么 C 会给出此错误 ‘size’ undeclared(在此函数中首次使用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26667041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com