I need an array with a limited size where I can push ints in.
Once the array is full the last one in the array needs to go out so there is a new spot in front so I can keep adding data. How can you do this in C?
this should be a reasonable implementation
#include <stdio.h>
#include <stdlib.h>
struct int_queue{
int *arr;
size_t size;
int len;
int first_elem;
};
void init_int_queue(struct int_queue *queue, size_t nelems)
{
queue->arr = malloc(nelems*sizeof(int));
queue->first_elem = 0;
queue->len = 0;
queue->size = nelems;
}
void destroy_int_queue(struct int_queue *queue)
{
free(queue->arr);
}
void push_int(struct int_queue *queue, int new_val)
{
queue->arr[(queue->first_elem + (queue->len)++) % queue->size] = new_val;
if (queue->len > queue->size){
queue->len--;
queue->first_elem++;
queue->first_elem %= queue->size;
}
}
int get_int(struct int_queue *queue, int index)
{
// note does not handle the case for index out of bounds
// wraps around for overflow
return queue->arr[(queue->first_elem + index) % queue->size];
}
void print_int_queue(struct int_queue *queue)
{
printf("[");
for(int i = 0; i < queue->len; ++i){
printf("%d", queue->arr[(queue->first_elem + i) % queue->size]);
if(i < queue->len - 1)
printf(", ");
}
printf("]\n");
}
int main(int argc, char *argv[])
{
struct int_queue queue;
init_int_queue(&queue, 100);
for(int i = 0; i < 150; ++i){
push_int(&queue, i);
}
print_int_queue(&queue);
destroy_int_queue(&queue);
return 0;
}
Not extensively tested but it's simply wrapping around the array everytime a new element is added, keeping track of the first element shifting if the length exceeds the size.
Related
I have this kind of code
typedef struct {
int x;
int y;
} Test;
Test* getTest(int *length) {
Test *toReturn = malloc(sizeof(Test));
// Some operations with realloc
return toReturn;
}
void printTest(Test *arrTest, int length) {
for(int i = 0; i < length; i++) {
// Some operations
}
}
int main() {
int testlength = 0;
Test *myTest = getTest(&testlength);
printTest(myTest, testLength) // Gives random numbers
}
Don't know why it gives random numbers, when I'm in the main tho (the whole code) it does not give these kinds of errors
Made minor changes to the code, see below:
#include <stdio.h>
typedef struct {
int x;
int y;
} Test;
Test* getTest(int *length) {
Test *toReturn = (Test *)malloc(sizeof(Test));
// Some operations with realloc
return toReturn;
}
void printTest(Test *arrTest, int length) {
printf("%d ", length);
for(int i = 0; i < length; i++) {
// Some operations
}
}
int main() {
int tlen = 0;
Test *myTest = getTest(&tlen);
printTest(myTest, tlen); // Gives random numbers
printf("....Exit....");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct arrayADT {
int *A;
int size;
int length;
int *B;
int arr3;
};
struct arrayADT * MergeArray(struct arrayADT *arr1, struct arrayADT *arr2) { //we create thus in heap cuz we need to be able to use these in main function
struct arrayADT *arr3 = (struct arrayADT *)malloc((sizeof(struct arrayADT)));
int i, j, k;
i = j = k = 0;
while(i < arr1->length && j < arr1->length ) {
if(arr1->A[i] < arr2->A[j]) {
arr3->A[k] = arr1->A[i];
k++;
i++;
}
else {
arr3->A[k] = arr2->A[j];
k++;
j++;
}
}
for(; i<arr1->length ; i++) {
arr3->A[k] = arr1->A[i];
k++;
}
for(; j < arr2->length ; j++) {
arr3->A[k] = arr2->A[j];
k++;
}
arr3->length = arr1->length + arr2->length;
arr3->length = 10;
}
void main() {
struct arrayADT arr;
printf("Enter the size of an array");
scanf("%d", &arr.size);
arr.A = (struct arrayADT *)malloc(arr.size * sizeof(int));
arr.length = 0;
int n;
printf("enter the number of elements in an array");
scanf("%d", &n);
printf("enter the elements");
for(int i = 0; i < n; i++) {
scanf("%d", &arr.A[i]);
}
arr.length = n;
display(arr);
printf("Enter second array");
int j;
struct arrayADT *B = (struct arrayADT *)malloc((sizeof(struct arrayADT)));
for(j = 0; j < arr.length; j++) {
scanf("%d", &B[j]);
}
struct arrayADT *arr3 = (struct arrayADT *)malloc(sizeof(struct arrayADT));
arr3 = MergeArray(&arr, &B);
display(*arr3);
I was looking to merge these arrays using heap memory and I am getting segmentation fault. I am new to C programming with pointers and I have been struck here it would be so helpful if I passed this barrier with your help.
And I am not getting where my error lies it would be helpful if someone specifies that too, so that I can avoid these errors in future.
PS: I am using minGW compiler.
In general, your code is rater unorganized. There are several cases for undefined behaviour, for example you don't scan in the second array correctly. The most probably candidate for your segmentaion fault is here:
struct arrayADT *arr3 = (struct arrayADT *)malloc((sizeof(struct arrayADT)));
This will give you an uninitialized chunk of memory. The length and size could of arr3 be anything, and its data field A does not point to valid memory. Accessing it will likely crash.
You have three arrays in your code. You construct each step by step and you treat each differently. That leads to errors easily. Let's go about this more systematically.
Let's create a struct type for a fixed-size array: The maximum size must be given on creation and cannot change. The actual length of the array may be anything from 0 to its maximum size.
typedef struct Array Array;
struct Array {
int *value; // data array
int length; // actual length, 0 <= length <= size
int size; // maximum capacity
};
We create such arrays on the heap and because initializing the members is error-prone, we write a constructor:
Array *array_create(int size)
{
Array *array = calloc(1, sizeof(*array));
array->size = size;
array->value = calloc(size, sizeof(*array->value));
return array;
}
This function creates an empty array for at most size integers. If we allocate memory, we must de-allocate it later, so let's write a corresponding destructor function, which cleans up the ressources:
void array_destroy(Array *array)
{
if (array) {
free(array->value);
free(array);
}
}
After destroying an array, it can no longer be used, just as with memory after calling free() on it.
The array is at first empty, so let's write a function to add elements at its end if there is room:
void array_push(Array *array, int x)
{
if (array->length < array->size) {
array->value[array->length++] = x;
}
}
And a function to print it:
void array_print(const Array *array)
{
printf("[");
for (int i = 0; i < array->length; i++) {
if (i) printf(", ");
printf("%d", array->value[i]);
}
printf("]\n");
}
Now you can create arrays like so:
Array *a = array_create(10);
for (int i = 0; i < a->size; i++) {
array_push(a, i);
}
array_print(a);
array_destroy(a);
Your merge function will be simpler, too. Here's a full example. (But is uses generated array, not arrays typed in by the user.)
#include <stdio.h>
#include <stdlib.h>
typedef struct Array Array;
struct Array {
int *value;
int length;
int size;
};
Array *array_create(int size)
{
Array *array = calloc(1, sizeof(*array));
array->size = size;
array->value = calloc(size, sizeof(*array->value));
return array;
}
void array_destroy(Array *array)
{
if (array) {
free(array->value);
free(array);
}
}
void array_push(Array *array, int x)
{
if (array->length < array->size) {
array->value[array->length++] = x;
}
}
void array_print(const Array *array)
{
printf("[");
for (int i = 0; i < array->length; i++) {
if (i) printf(", ");
printf("%d", array->value[i]);
}
printf("]\n");
}
Array *merge(Array *a, Array *b)
{
Array *res = array_create(a->length + b->length);
int i = 0;
int j = 0;
while(i < a->length && j < b->length) {
if(a->value[i] < b->value[j]) {
array_push(res, a->value[i++]);
} else {
array_push(res, b->value[j++]);
}
}
while(i < a->length) {
array_push(res, a->value[i++]);
}
while(j < b->length) {
array_push(res, b->value[j++]);
}
return res;
}
int main(void)
{
Array *a = array_create(10);
Array *b = array_create(6);
Array *c;
for (int i = 0; i < a->size; i++) {
array_push(a, 1 + 3 * i);
}
for (int i = 0; i < b->size; i++) {
array_push(b, 4 + 2 * i);
}
array_print(a);
array_print(b);
c = merge(a, b);
array_print(c);
array_destroy(a);
array_destroy(b);
array_destroy(c);
return 0;
}
If you've read so far, here's the lowdown:
Organzie your code. That applies to code layout as much as writing small, generally applicable functions instead of doing everything "by hand". (The array type above is a bit on the fence: It uses functions, but getting at the data is still done via accessing the struct fields. You could even change the szie and length, whixh shouldn't really happen.)
Enable compiler warnings with -Wall. You will get useful information about potential (and often actual) errors.
Good luck!
I'm trying to come up with a rudimentary radix sort (I've never actually seen one, so I'm sorry if mine is awful), but I am getting an EXC_BAD_ACCESS error on the line link = *(link.pointer);. My C skills aren't great, so hopefully someone can teach me what I'm doing wrong.
I'm using XCode and ARC is enabled.
Here is the code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#define ARRAY_COUNT 10
#define MAX_VALUE 1000000
#define MODULO 10.0f
typedef enum
{
false,
true
} bool;
typedef struct linkedListStruct
{
int value;
struct linkedListStruct *pointer;
} LinkedList;
void radixSort(int *array);
bool arraySorted(int *array);
int * intArray(int minValue, int maxValue);
int main(int argc, const char * argv[])
{
int *sortingArray = intArray(0, MAX_VALUE);
radixSort(sortingArray);
printf("Array %s sorted", arraySorted(sortingArray) ? "" : "not");
return 0;
}
void radixSort(int *array)
{
int numberOfIterations = (int)ceilf(log(MAX_VALUE)/log(MODULO));
for(int n = 0; n < numberOfIterations; n++)
{
LinkedList *linkedListPointers[(int)MODULO] = {0};
int i = ARRAY_COUNT;
while(i--)
{
int location = (int)floor((array[i] % (int)powf(MODULO, n + 1))/powf(MODULO, n));
LinkedList link = { array[i], NULL };
link.pointer = linkedListPointers[location];
linkedListPointers[location] = &link;
}
int location = 0;
for(int pointerSelection = 0; pointerSelection < MODULO; pointerSelection++)
{
if(linkedListPointers[pointerSelection])
{
LinkedList link = { 0, linkedListPointers[pointerSelection] };
linkedListPointers[pointerSelection] = NULL;
while(link.pointer)
{
link = *(link.pointer);
array[location++] = link.value;
}
}
}
}
}
bool arraySorted(int *array)
{
int i = ARRAY_COUNT;
while(--i)if(array[i - 1] > array[i])break;
return !i;
}
int * intArray(int minValue, int maxValue)
{
int difference = maxValue - minValue;
int *array = (int *)malloc(sizeof(int) * ARRAY_COUNT);
int i;
for(i = 0; i < ARRAY_COUNT; i++)
{
array[i] = rand()%difference + minValue;
}
return array;
}
Also, if someone wants to suggest improvements to my sort, that would also be appreciated.
The problem came from how I was allocating the linked list. I changed
LinkedList link = { array[i], NULL };
link.pointer = linkedListPointers[location];
to
LinkedList *link = malloc(sizeof(LinkedList));
link->value = array[i];
link->pointer = linkedListPointers[location];
In the first example, the pointer to link remained the same through each loop iteration (I wasn't aware it would do that), so I needed to make the pointer point to a newly allocated memory chunk.
EDIT:
Changing that also had me change from
while(link.pointer)
{
link = *(link.pointer);
array[location++] = link.value;
}
to
while(linkPointer)
{
link = *linkPointer;
array[location++] = link.value;
linkPointer = link.pointer;
}
When I'm trying to sort array content, which I have referenced via double-pointer.
http://ideone.com/OapPh
line 77
SortQuick(&(*data_resource)->data,
&(*data_resource)->low,
&(*data_resource)->length - 1);
The content hasn't been sorted, via the same method I'm printing values of this array very fine with the function ArrayPrint()
This code compiles well on MS C++ compiler, about GCC don't know.
There are not any warning in the code or errors, MS compiler doesn't show it by standard configuration.
It's not sorting because &(*data_resource)->length - 1 evaluates to &(*data_resource)->low.
&(*data_resource)->length is a pointer to an int. When you subtract 1 from it, it points to the int just before and that happens to be &(*data_resource)->low because you defined the structure members in precisely this order:
typedef struct Resource
{
int low;
int length;
int *data;
} Resource;
So, your sorting code gets 2 identical indices to work with and rightly does not sort anything as there's nothing to sort in a subarray consisting of just one element.
Here's a slightly modified version that works:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Resource
{
int low;
int length;
int *data;
} Resource;
void Swap(int *first, int *second)
{
int tmp = *first;
*first = *second;
*second = tmp;
}
void SortQuick(int **data, int *low, int *high)
{
int i = *low,
j = *high,
x = (*data)[(*low + *high) / 2];
do
{
while((*data)[i] < x) i++;
while((*data)[j] > x) j--;
if(i <= j)
{
Swap(&(*data)[i], &(*data)[j]);
i++;
j--;
}
} while(i <= j);
if(i < *high) SortQuick(data, &i, high);
if(*low < j) SortQuick(data, low, &j);
}
void ArrayPrint(int **data, int *array_length)
{
for(int i = 0; i < *array_length; i++)
{
printf("[%i]: %20i\r\n", i, (*data)[i]);
}
}
void ArrayInit(int **data, int *array_length)
{
(*data) = (int*)malloc(sizeof(int) * *array_length);
for(int i = 0; i < *array_length; i++)
{
(*data)[i] = rand();
}
}
int GlobalInit(Resource **data_resource)
{
srand((unsigned int)rand());
*data_resource = (Resource*)malloc(sizeof(Resource));
(*data_resource)->low = 0;
(*data_resource)->length = 10;//rand();
ArrayInit(&(*data_resource)->data, &(*data_resource)->length);
return (*data_resource)->length;
}
void BenchmarkTest(Resource **data_resource)
{
ArrayPrint(&(*data_resource)->data, &(*data_resource)->length);
(*data_resource)->length--;
SortQuick(&(*data_resource)->data, &(*data_resource)->low, &(*data_resource)->length);
(*data_resource)->length++;
ArrayPrint(&(*data_resource)->data, &(*data_resource)->length);
}
int main(void)
{
Resource *data_resource = NULL;
GlobalInit(&data_resource);
BenchmarkTest(&data_resource);
return 0;
}
Output (ideone):
[0]: 1362961854
[1]: 8891098
[2]: 392263175
[3]: 158428306
[4]: 2074436122
[5]: 47170999
[6]: 431826012
[7]: 1599373168
[8]: 1769073836
[9]: 1043058022
[0]: 8891098
[1]: 47170999
[2]: 158428306
[3]: 392263175
[4]: 431826012
[5]: 1043058022
[6]: 1362961854
[7]: 1599373168
[8]: 1769073836
[9]: 2074436122
All of those references and dereferences of pointers are driving you mad, and in most cases they aren't necessary, try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Resource
{
int low;
int length;
int *data;
} Resource;
void Swap(int *first, int *second)
{
int tmp = *first;
*first = *second;
*second = tmp;
}
void SortQuick(int *data, int low, int high)
{
int i = low,
j = high,
x = data[(low + high) / 2];
do
{
while(data[i] < x) i++;
while(data[j] > x) j--;
if(i <= j)
{
Swap(&(data[i]), &(data[j]));
i++;
j--;
}
} while(i <= j);
if(i < high) SortQuick(data, i, high);
if(low < j) SortQuick(data, low, j);
}
void ArrayPrint(int *data, int array_length)
{
for(int i = 0; i < array_length; i++)
{
printf("[%i]: %i\r\n", i, data[i]);
}
}
void ArrayInit(Resource *data_resource)
{
data_resource->data = (int*)malloc(sizeof(int) * data_resource->length);
for(int i = 0; i < data_resource->length; i++)
{
data_resource->data[i] = rand();
}
}
Resource* GlobalInit()
{
Resource *data_resource;
srand((unsigned int)rand());
data_resource = (Resource*)malloc(sizeof(Resource));
data_resource->low = 0;
data_resource->length = rand();
ArrayInit(data_resource);
return data_resource;
}
void BenchmarkTest(Resource *data_resource)
{
ArrayPrint(data_resource->data, data_resource->length);
SortQuick(data_resource->data, data_resource->low, data_resource->length - 1);
ArrayPrint(data_resource->data, data_resource->length);
}
int main(void)
{
Resource *data_resource = NULL;
data_resource = GlobalInit();
BenchmarkTest(data_resource);
return 0;
}
This part doesn't make sense:
&(*data_resource)->length - 1);
You are taking the address of the length field and substracting 1. Removing the - 1 seems to make it work.
Besides, you are overusing pointers. E.g. ArrayPrint could simply be
void ArrayPrint(int *data, int array_length)
{
for(int i = 0; i < array_length; i++)
{
printf("[%i]: %i\r\n", i, data[i]);
}
}
gcc compiles the following code without error. I'm creating a bubble sort function that can be used with arrays of any data type (hence the function pointer).
It sorts the array of character strings (arr2) without a problem, however, I can't figure out why it won't properly sort the array of integers (arr). I added a printf statement in the compare_long function to see what is going on. It doesn't look like the integers are being passed to it properly. Any help will be greatly appreciated.
#include <stdio.h>
#include <string.h>
#define MAX_BUF 256
long arr[10] = { 3,6,1,2,3,8,4,1,7,2};
char arr2[5][20] = { "Mickey Mouse",
"Donald Duck",
"Minnie Mouse",
"Goofy",
"Pluto" };
void bubble(void *p, int width, int N, int(*fptr)(const void *, const void *));
int compare_string(const void *m, const void *n);
int compare_long(const void *m, const void *n);
int main(void) {
int i;
puts("\nBefore Sorting:\n");
for(i = 0; i < 10; i++) { /* show the long ints */
printf("%ld ",arr[i]);
}
puts("\n");
for(i = 0; i < 5; i++) { /* show the strings */
printf("%s\n", arr2[i]);
}
bubble(arr, 4, 10, compare_long); /* sort the longs */
bubble(arr2, 20, 5, compare_string); /* sort the strings */
puts("\n\nAfter Sorting:\n");
for(i = 0; i < 10; i++) { /* show the sorted longs */
printf("%d ",arr[i]);
}
puts("\n");
for(i = 0; i < 5; i++) { /* show the sorted strings */
printf("%s\n", arr2[i]);
}
return 0;
}
void bubble(void *p, int width, int N, int(*fptr)(const void *, const void *)) {
int i, j, k;
unsigned char buf[MAX_BUF];
unsigned char *bp = p;
for(i = N - 1; i >= 0; i--) {
for(j = 1; j <= i; j++) {
k = fptr((void *)(bp + width*(j-1)), (void *)(bp + j*width));
if(k > 0) {
memcpy(buf, bp + width*(j-1), width);
memcpy(bp + width*(j-1), bp + j*width , width);
memcpy(bp + j*width, buf, width);
}
}
}
}
int compare_string(const void *m, const void *n) {
char *m1 = (char *)m;
char *n1 = (char *)n;
return (strcmp(m1,n1));
}
int compare_long(const void *m, const void *n) {
long *m1, *n1;
m1 = (long *)m;
n1 = (long *)n;
printf("m1 = %l and n1 = %l\n", *m1, *n1);
return (*m1 > *n1);
}
The ANSI C spec defines long as a MINIMUM of 4 bytes (32 bits) but GCC is defining long as 8 bytes in your case. It is architecture-specific so you need to use sizeof(long) or one of the C99 types like uint32_t or int32_t if you want a specific size.