简体   繁体   English

从函数返回指针

[英]Return Pointer from function

I am new in C and literally trying to return pointer from my function to the pointer variable and have this "[Warning] assignment makes pointer from integer without a cast" no idea why compiler defines it as an int.我是 C 新手,字面上试图将指针从我的函数返回到指针变量,并且有这个“[警告] 赋值使指针来自整数而不进行强制转换”不知道为什么编译器将它定义为 int。 Can't declare my function before main as well, it throws this "undefined reference to `free_block'".也不能在 main 之前声明我的函数,它会抛出这个“对‘free_block’的未定义引用”。

#include <stdio.h>
#include <stdlib.h>
    struct block{
    int num;
};

int main(int argc, char *argv[]) {
    struct block *b;
    b = free_block();

    struct block *free_block(){
        struct block *b = NULL;
        return b;
    }
    return 0;
}

Thank you谢谢

Yea, my fault I know not too much about c syntax and had no idea about nested functions, soz.是的,我的错,我对 c 语法知之甚少,也不知道嵌套函数,soz。 But what could be wrong in this case: I am trying to make my own memory allocator without using malloc or calloc functions.但是在这种情况下可能有什么问题:我试图在不使用 malloc 或 calloc 函数的情况下制作自己的内存分配器。 In my code I have the same Warning on the line with pointer = free_space_get(size);在我的代码中,我在pointer = free_space_get(size);行上有相同的警告pointer = free_space_get(size); , here I have no more nested func(), my methods defined before main(), but still have no idea do I have to declare my functions or no, coz in the answer given to me it worked fine as soon as functions were defined before the main(). ,这里我没有更多的嵌套 func(),我在 main() 之前定义的方法,但仍然不知道我是否必须声明我的函数或不,因为在给我的答案中,它在函数定义后就可以正常工作在 main() 之前。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct header{
        size_t size;
        struct header *next;
        unsigned int free;
    };
void *m_alloc(size_t  size){
        size_t total_size;
        void *block;
        struct header *pointer;
        if(!size)  
            return NULL;
        pointer = free_space_get(size);
        if(pointer){
            pointer->free = 0;
            return (void*)(pointer + 1);
        }

    }
struct header *get_free_space(size_t size){
        struct header *b = NULL;
        return b;
    }

int main() {
    return 0;
}

Your code can be re-written as您的代码可以重写为

#include <stdio.h>
#include <stdlib.h>

struct block{
    int num;
};

struct block *free_block(){
        struct block *b = NULL;
        return b;
}

int main(int argc, char *argv[]) {

    struct block *b;
    b = free_block();

    if(b == NULL) // Checking whether pointer is returned
        printf("\n Recieved NULL \n");

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM