0
votes

I have created a simple program. basically I created struct pointer in main and two functions. One function is simply allocating space for ads->title which is char array. Assume at compile time I don't know the sizeof title, the second function is allocating memory for struct so this function can take any type of struct and not just single struct type. But when I compile the program with -Wall Wextra -Werror I get plenty of errors like this

warning: assignment to ‘char’ from ‘void *’ makes integer from pointer without a cast [-Wint-conversion]

11 | *arr= malloc(sizeof(char)*n);

and many more. Thanks for any help

All I am trying to do this with pointers and void pointers

#include <stdio.h>
#include <malloc.h>
struct ads{
    int id;
    char *title;
    char *name;
};

void get_alloc_string(char *arr,int n)
{
    *arr= malloc(sizeof(char)*n);
}

void get_alloc_single_struct(void **arr)
{
    arr=malloc(sizeof(struct ads));
}

int main()
{

    struct ads *data1;
    //data1->id=102;
    get_alloc_single_struct(data1);
    get_alloc_string(data1->title,10);
    data1->title="fawad khan";
    data1->id=102;
    printf("%s %d\n",data1->title,data1->id);


    //get_alloc_string(data1->title);
    return 0;

}
1
probably you should typecast the void ptr to char* - Abhilekh Gautam
Your get_alloc_string makes no sense. If you're trying to emulate pass-by-reference (instead of the more natural and simple return) you need to pass a pointer to the pointer using the pointer-to operator &. When you do *arr = malloc(...) you try to assign the pointer returned by malloc to arr[0] which makes no sense. - Some programmer dude

1 Answers

2
votes

Both allocation functions are wrong, but for different reasons:

void get_alloc_string(char *arr,int n)
{
    *arr= malloc(sizeof(char)*n);
}

That should be:

void get_alloc_string(char **arr,int n)
                        /* ^ extra indirection */
{
    *arr= malloc(sizeof(char)*n);
}

As you want to return the pointer.

void get_alloc_single_struct(void **arr)
{
    arr=malloc(sizeof(struct ads));
}

That should be:

void get_alloc_single_struct(void **arr)
{
    *arr=malloc(sizeof(struct ads));
 /* ^ extra indirection */
}

As you want again to return the pointer.

Personally, I'd change the function to something like this:

char *get_alloc_string(size_t n)
{
    return malloc(sizeof(char)*n);
}

And similar for get_alloc_single_struct().