I have a struct and an dynamic array inside the struct. I want to malloc this array but i don't really now how. I want that array void because i want the members of this array to be structs. As you can see i tried something but it doesn't really work
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct saf
{
int head;
void **stack;
int size;
}exp1;
void init(int n)
{
struct saf exp1->stack = malloc(n);
}
int main()
{
printf("Give size: ");
scanf("%d",&exp1.size);
init(exp1.size);
return 0;
}
exp1 isn't a pointer. Use
exp1.stack = malloc(n);
I believe you are looking for void *, e.g.,
void init (int n)
{
exp1->stack = malloc(sizeof(void *) * n);
}
You will have to cast it when you use it.
struct saf exp1.stack = malloc(n);
The above statement creates array of n memory locations and returns the void * pointer to the starting address. In this case stack should be single pointer i,e void *stack;
If you want stack to be a double pointer i,e void **stack then you should use
exp1.stack=malloc(sizeof(void *)*n);
Related
typedef struct
{
void **heapArr;
int last;
int capacity;
int (*compare) (void *arg1, void *arg2);
} HEAP;
int heap_Insert( HEAP *heap, void *dataPtr);
I was doing my assignment of insert data to heap with abstract data type.
I allocated memory to heap, but I got problem of inserting data to heap.
I can't find out how to make void double pointer to char or int arrays.
void *x=dataPtr;
heap->(*heapArr)=&x;
I tried this way but I got failed. How can I make void double pointer to other type?
Why heapArr is a double pointer ? I think a single pointer is enought...
typedef struct
{
void *heapArr;
int last;
int capacity;
int (*compare) (void *arg1, void *arg2);
} HEAP;
int heap_Insert( HEAP *heap, void *dataPtr){
heap->heapArr = dataPtr;
return 0;
}
int main(void){
char str[] = "hello";
HEAP heapString;
heap_Insert(&heapString, str);
char * str_get = heapString.heapArr;
printf("%s\r\n", str_get );
int val = 101;
HEAP heapInt;
heap_Insert(&heapInt, &val);
int * int_get = heapInt.heapArr;
printf("%i\r\n", *int_get);
}
If you want to convert void* to char*, then following is the method -
(say void *data)
char *a = (char*) data;
Similarly for double pointer,
char **a = (char**) heapArr;
Simply typecast will do the conversion. Please try and comment back what you see.
I am trying to implement on my own (in order to understand it better) the Stack data structure in C language.
Here is what I've got so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack{
//Data_Strucure: Stack of intgers
int *stack;
int size_of_stack;
int elem_in_stack;
};
struct stack *creat_stack(unsigned int);
int push(struct stack *, int);
int pop(struct stack *);
int empty(struct stack *);
int peek(struct stack *);
int main(int argc, char *argv[]){
int new_elem = 13;
struct stack *new_stack = creat_stack(5);
printf("%d %d\n", new_stack->size_of_stack, new_stack->elem_in_stack);
//Crashes from here
push(new_stack, new_elem);
printf("%d\n", new_stack->stack[new_stack->size_of_stack]);
}
struct stack *creat_stack(unsigned int size){
struct stack tmp;
struct stack *ret_stack = &tmp;
if((ret_stack->stack = malloc(sizeof(int) * size)) == NULL){
fprintf(stderr, "Unable to allocate memory for the Stack.\n");
exit(1);
}
ret_stack->size_of_stack = size;
ret_stack->elem_in_stack = 0;
return ret_stack;
}
int push(struct stack *stack, int nw_elem){
int pos = stack->size_of_stack - stack->elem_in_stack;
if(stack->size_of_stack == 0)
return 1;
stack->stack[pos] = nw_elem;
}
The compiler returns me no error. Though I don't understand why it crashes after push() is called.
Please, if possible, instead of solution code, can you just tell me where the error is? This way I can understand how it effect the whole program and try to solve it on my own (so next time won't happen again).
Thanks is advance for any of your usefull answers.
At least the function creat_stack is incorrect.
struct stack *creat_stack(unsigned int size){
struct stack tmp;
struct stack *ret_stack = &tmp;
//...
return ret_stack;
}
It returns a pointer to the local object tmp that will not be alive after exiting the function. So the returned pointer will be invalid and dereferencing such a pointer invokes undefined behavior.
Instead you could return the object itself from the function. That is the function declaration could look like
struct stack creat_stack(unsigned int size);
And in main you can write
struct stack new_stack = creat_stack(5);
Also the function push does not change the data member elem_in_stack And again it invokes undefined behavior because when elem_in_stack is equal to 0 then the function tries to write to memory outside the dynamically allocated array. That is in this case pos is equal to size_of_stack.
int push(struct stack *stack, int nw_elem){
int pos = stack->size_of_stack - stack->elem_in_stack;
if(stack->size_of_stack == 0)
return 1;
stack->stack[pos] = nw_elem;
}
I have a problem to sort an array (dynamically allocated) in a structure. Firstly, the idea was to order the array i in the structure in an ascendant order. Then I was thinking to order the array i maintaining instead the array j with the same "relationship" obtained when it was constructed the initial structure. I try to work for the first idea, but without any result with qsort.So this is my code... Any ideas? I think there is a problem in the construction of the comparing function..
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int M =10;
int N =30;
int K = 10;
struct element {
int *i;
int *j;
int k;
};
struct element *create_structure();
void print_element(struct element *);
int compare (const void *, const void * );
struct element * sort(struct element *);
main()
{
srand(time(NULL));
struct element *lista;
int count;
lista=create_structure();
print_element(lista);
printf("\n");
lista=sort(lista);
}
struct element *create_structure()
{
int aux1,aux2,count,load;
struct element *structure;
structure = (struct element *) malloc (M*sizeof(struct element *));
structure->k=K;
structure->i= (int *)malloc(structure->k*sizeof(int));
structure->j=(int *)malloc (structure->k*sizeof(int));
for (count = 0; count < K; count ++)
{
aux1=rand()%N;
(structure->i)[count]=aux1;
do
{
aux2=rand()%N;
}while(aux2==aux1);
(structure->j)[count]=aux2;
}
return (structure);
}
void print_element(struct element *lista)
{
int count;
for(count = 0; count < K; count ++)
{
printf("%d %d\n",lista->i[count],lista->j[count]);
}
}
int compare(const void *a, const void *b)
{
struct element *ia = (struct element *)a;
struct element *ib = (struct element *)b;
int *ptr1=(ia->i);
int *ptr2=(ib->i);
return (*ptr1-*ptr2);
}
struct element * sort(struct element *list)
{
qsort(list, sizeof(list->i)/ sizeof(int) , sizeof(list->i), compare);
//qsort(list->i, K, sizeof(list->i), compare);
print_element(list);
return (list);
}
Sorry for being late to the party ! :)
So let's start first by mentioning the wrong statements in your code
>> First
in function create_structure() you want to allocate memory for your structure pointer
struct element *structure; // here your structure pointer is
//pointing to memory space of type struct element
structure = (struct element *) malloc (M*sizeof(struct element *));
|------------------------|
|
V
Here you are allocating memory space of type struct element* which is
wrong ! instead it must be sizeof(struct element)
Concerning the while loop in the same function I found that it is totally useless
aux1=rand()%N;
(structure->i)[count]=aux1; // the value is in aux1 variable
do
{
aux2=rand()%N;
}while(aux2==aux1); // the loop try to get the same value of aux1
// or you have just stored it in aux1
(structure->j)[count]=aux2; // it is easy to delete the while loop and
// change aux2 by aux1
>> Second
Concerning the sort
qsort(list, sizeof(list->i)/ sizeof(int) , sizeof(list->i), compare);
|-----|
|
V
It is not an adress of the array so it is Wrong !
after knowing the major problems here is a version of code based on your own code which works perfectly
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int M =10;
int N =30;
int K = 10;
struct element {
int *i;
int *j;
int k;
};
struct element *create_structure();
void print_element(struct element *);
int compare (const void *, const void * );
void sort(struct element *); // changed the return value of sort
// to void as the argument will be changed directly because it is a
// pointer
int main()
{
srand(time(NULL));
struct element *lista;
lista=create_structure();
printf("\n--------- i --- j ---------\n\n");
print_element(lista);
printf("\n---------------------------\n");
sort(lista);
print_element(lista);
return 0;
}
struct element *create_structure()
{
int aux1=0,count=0;
struct element *structure;
// Changed the allocation of structure pointer
structure = (struct element *) malloc (sizeof(struct element));
structure->k=K;
structure->i= (int *)malloc(K*sizeof(int));
structure->j=(int *)malloc (K*sizeof(int));
for (count = 0; count < K; count ++)
{
aux1=rand()%N;
// we kept only the first aux1 and copied it in the two arrays
(structure->i)[count]=aux1;
(structure->j)[count]=aux1;
}
return (structure);
}
void print_element(struct element *lista)
{
int count=0;
for(count = 0; count < K; count++)
{
printf("row=%2d : %2d %2d\n",count+1,(lista->i)[count],(lista->j)[count]);
}
}
int compare(const void *a, const void *b)
{
// compare the values of two case of array pointed by i of type int
return *(int*)a-*(int*)b;
}
void sort(struct element *list)
{
// we will sort the array pointed by i which contains K elements
// of type int and size sizeof(int) by using the compare function
qsort(list->i, K , sizeof(int), compare);
}
Hope it helps ! :)
Note: Using this code in codeblocks v13.12 generates under linux (gcc version 4.8.2) wrong output !! [ It might be a BUG in Code::Blocks]
but using it with command line with gcc gives correct output !!
I create a Queue that includes a two dimensional array, the size of every element of that array is 2. An Exception occurs when I enqueue a 2-size array in the queue.
The following is my code:
#include "stdio.h"
#define size 1000
typedef struct Queue {
int *data[2];
int front;
int rear;
}Queue;
void init(Queue *q)
{
q->front=0;
q->rear=0;
}
void Enqueue(Queue *q,int *value)
{
if(q->rear==size)
return ;
q->data[q->rear++]=value;
}
void main()
{
Queue q[1];
init(q);
int a[10][2];
for(int i=0;i<10;i++) {
a[i][0]=i;
a[i][1]=i*2+1;
Enqueue(q,a[i]);
}
}
*I create a Queue that includes a two dimensional array*
No you just create a pointer array in onw dimensional by int *data[2];
If you want create a Quene that include a two demensional array , it will be int data[size][size_anoter]
However, you didn't need I two dimensional . In void Enqueue(Queue *q,int *value) function , you pass the address from a[i] to data[i] . So you only need a big enough pointer array ;\
int * data[size];
Besides , It is better if you can define size as SIZE.
probably, Feel like the following
#include <stdio.h>
#include <stdlib.h>
#define size 1000
typedef struct Queue {
int (**data)[2];
int front;
int rear;
} Queue;
void init(Queue *q){
q->front=0;
q->rear=0;
q->data = malloc(size*sizeof(int (*)[2]));
}
void Enqueue(Queue *q,int (*value)[2]){
if(q->rear==size)
return ;
q->data[q->rear++]=value;
}
int main(){
Queue q[1];
init(q);
int a[10][2];
for(int i=0;i<10;i++) {
a[i][0]=i;
a[i][1]=i*2+1;
Enqueue(q, &a[i]);
}
//printf("%d\n", (*q->data[0])[1]);
return 0;
}
I can see at least a couple of issues:
typedef struct Queue {
int *data[2];
This is not a pointer to a two-dimensional array of ints, which I assume was what was intended. It is an array of two int pointers.
For a 2D array of 1000 entries of arrays with two elements, you probably wanted:
typedef struct Queue {
int data[size][2];
Then, when you call Enqueue(), copy in the array of two ints into the appropriate entry indicated by rear:
void Enqueue(Queue *q,int value[2])
{
if(q->rear==size)
return ;
memcpy(q->data[q->rear], value, sizeof(q->data[q->rear]));
q->rear++;
}
This solution will make a fixed array. If you want the array to be built dynamically it is a little more complicated as you need to malloc/calloc the memory and then free it when done.
I have a problem with dynamic memory allocation. Here is the code so please help.
#include <stdio.h>
int i;
typedef struct{
int A;
}node;
typedef struct Model
{
node *m;
} Model;
Model M;
void initialize(Model *a, int size)
{
a->m = (node*) malloc(size);
}
void model_init(Model *a, int len)
{
int i;
for (i=0;i<len;i++) a->m[i].A = 20;
}
int main()
{
initialize(&M ,10);
model_init(&M, 10);
for (i=0;i<10;i++) printf("%d\n",M.m[i].A);
}
I am trying to make a Model that has 10 nodes and I want to assign values to nodes in variable A. The printf shows (-1819044973, -1819044973, 14128019, 3969, 0, 0, 0 ...)
I just want it to say for example M.m[2].A=20
What am I doing wrong? please help.
TY
void initialize(Model *a, int size)
{
a->m = (node*) malloc(sizeof(node) *size); // NOTICE HERE!!!!
}
Your initialize function allocates a number of bytes then model_init later assumes that many node instances will be available. node is larger than 1 byte (at least sizeof(int) bytes) so you write beyond the end of allocated memory.
The easiest fix is to change initialize:
void initialize(Model *a, int elements)
{
a->m = malloc(elements * sizeof(node));
}
For more information on the fact that you don't have to cast malloc :
Do I cast the result of malloc?