John John John John - 3 years ago 176
C Question

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.
Can't declare my function before main as well, it throws this "undefined reference to `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.
But what could be wrong in this case:
I am trying to make my own memory allocator without using malloc or calloc functions. In my code I have the same Warning on the line with
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().

#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;
}

Answer Source

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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download