Cannot enqueue array value - c

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.

Related

Why do we need to leave an empty cell in a circular queue to determine whether it is empty or not?

I just learned about circular queues in class and I'm still confused, I know that without the empty cell we wouldn't be able to distinguish between an empty queue and a a queue with one element, but why ?
I used f.h for prototypes and f.c as implementation:
f.h:
#define n 50
struct queue
{
int key[n];
unsigned head;
unsigned tail;
};
void cree(struct queue *);
unsigned empty(struct queue);
int first(struct queue);
void enqueue(int, struct queue *);
void dequeue(struct queue *);
then f.c:
#include <assert.h>
#include "f.h"
void cree(struct queue *q)
{
q->head = 0;
q->tail = 0;
}
unsigned empty(struct queue q)
{
return (q.head == q.tail);
}
int first(struct queue q)
{
unsigned i;
assert(!empty(q));
i = q.head + 1;
if(i>n-1)
{
i = 0;
}
return(q.key[i]);
}
void enqueue(int x, struct queue *q)
{
q->tail++;
if(q->tail>n-1)
{
q->tail = 0;
}
assert(q->head != q->head);
q->key[q->tail] = x;
}
void dequeue(struct queue *q)
{
assert(!empty(*q));
q->head++;
if(q->head>n-1)
{
q->head =0 ;
}
}
You've got this a little bit wrong in 2 ways. The first way is that the confusion is between an empty queue and a full queue, not a queue with 1 element. Keeping one cell empty changes what it means to be "full".
So, given a circular queue, how do you determine how many elements it has in it?
You would like to write size = (end_position - start_position) % array_length. In fact, the % operator probably doesn't work like you want in your language, though, so you'll write size = (array_length + end_position - start_position) % array_length
If the queue is empty, you get size == 0, which is what you want. If the queue has array_length elements in it, though, you also get size == 0, which is wrong. You can fix that by ensuring that the number of elements is always less than the array length.
The other way you have this wrong is the "wouldn't be able to" part. It's almost always wrong to say that. If you store start_position and size, for example, instead of start_position and end_position, then it's easy to distinguish full from empty, and you can put array_length elements in your queue.

Sorting dynamic array in a structure with C qsort ()

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 !!

Trouble accessing a struct member from a void pointer.

I am not too experienced in C and I am having trouble with something that might be simple you for most of you. Basically, I have this structure that defines a 'generic' queue with a resizing array implementation:
typedef void (*free_fptr)(void *);
typedef struct {
void **queue; // pointer to generic type
size_t first; // head index in array
size_t last; // tail index in array
size_t size; // number of elements
size_t capacity; // capacity of array
size_t elem_size; // size in bytes of each element in queue
free_fptr deleter; // function used to free each element
} Queue;
Now, I have a data type that I want to put in the queue :
typedef struct {
Process_state state;
Queue time_queue;
unsigned int start_time;
unsigned int id;
} Process;
I also have a function 'Queue_destroy(Queue *q)' that I want to call when I need to free each element in the queue :
void
Queue_destroy(Queue *q)
{
size_t i;
for (i = 0; i < q->size; ++i) {
q->deleter(q->queue[(q->first + i) % q->capacity]);
}
free(q->queue);
}
Now, my problem is that I don't know to access to the 'Process' queue inside the queue from a void pointer. For example :
void
Process_deleter(void *item)
{
// Here I want to access the queue inside (Process *)item
free((Process *)item);
}
I tried many things without success such as :
Queue_destroy((*(Process *)item).time_queue);
Queue_destroy((Process *)item->time_queue);
It does not compile and I am clueless!
Any help would be greatly appreciated!
Your function:
Queue_destroy(Queue *q)
expects a Queue*
So, change:
Queue_destroy((*(Process *)item).time_queue); // Here you are passing the object
to:
Queue_destroy(&(((Process *)item)->time_queue));
Assuming item is a pointer to your struct Process

Malloc Member Array of Struct

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);

Dynamic allocation of structs in C

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?

Resources