i wasn't able to do a dynamic array of function pointers, i have troubles understanding how to work with a dynamic array of function pointers when having a pointer to the func_cmp pointer.
int(*func_cmp[])(void *,void*);
numElements++;
func_cmp=(func_cmp*)realloc(func_cmp, numElements*sizeof(func_cmp*));
func_cmp[numElements-1]=*func_cmp;
i'm not sure about the realloc line.
Clearest way is to use typedef
#include <stdlib.h>
typedef int (*functype)(void *a, void *);
functype funcs[100]; // static array
functype *moreFuncs; // dynamic array
int main() {
int capacity = 16; // initial capacity
int n = 0; // initial size
moreFuncs = malloc(capacity*sizeof(functype)); // heap dynamic array
// ...
// adding element and need more space
if (n >= capacity) {
capacity *= 2;
moreFuncs = realloc(moreFuncs, capacity);
moreFuncs[n++] = <address of new function>;
}
}
Related
Let's say I have a struct for implementing vectors in C like this:
struct cvector {
unsigned int size; // indicates number of element in the vector
unsigned int capacity; // indicates length of the array
int* data; // array to store the actual data
};
typedef struct cvector* cvector;
Then I create this vector like this:
cvector cvector_create() {
cvector retval = (cvector)malloc(sizeof(struct cvector));
retval->capacity = 8;
retval->size = 0;
retval->data = (int*)malloc(retval->capacity * sizeof(int));
return retval;
}
I use malloc for both allocating memory for the struct and for allocating memory for the internal int array.
For freeing up my cvector I use this:
void cvector_free(cvector vector) {
free(vector);
}
My question is, do I need to free the internal int array as well separately like this: free(vector->data) or is freeing up only the struct is enough?
Yes, you need to free also vector->data, the rule is: one call to free per each call to malloc
if you are under C99, you can use flexible array members:
struct cvector {
unsigned int size; // indicates number of element in the vector
unsigned int capacity; // indicates length of the array
int data[]; // array to store the actual data
};
Notice that int data[]; must be the last member of the struct.
Then, you reserve space in this way:
cvector cvector_create() {
cvector retval = malloc(sizeof(struct cvector) + (sizeof(int) * 8));
retval->capacity = 8;
retval->size = 0;
return retval;
}
Now, calling free(vector) is enough since vector and vector->data are on the same block.
I'm new to programming and to C, and I just learned about structs. I'm trying to use them to make an array which can change size as required (so, if the array gets full, it creates a new array double the size, copies the old array into the new one and deletes the old one). All I've done so far is create the struct and the functions for setting it up, and already I'm having problems. The main problem is that, sometimes when I run it it does exactly what I expect it to, which is create the struct, return a pointer to said struct, and then print all elements of the contained array. Other times when I run it, it does nothing at all! I don't get how it can work sometimes, and sometimes not! Obviously i'm doing something really wrong, but I can't work out what. Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int cap;
int used;
void (*cpy) (int *, const int *, int);
//void (*append) (int);
int array[];
} dynArray;
dynArray * new_dynArray(int *, int);
void copy(int *, const int *, int);
int main(void) {
int start_arr[] = {1,2,3,4,5,6};
// create new dynArray, pass start array and number of elemnts
dynArray *arr = new_dynArray(start_arr, \
sizeof(start_arr) / sizeof(start_arr[0]));
// print all elements of dynArray
for (int i=0; i<(arr->used); i++) {
printf("%d, %d\n", arr->array[i], i);
}
free(arr);
return 0;
}
dynArray * new_dynArray(int init_arr[], int size) {
//printf("%d", size);
// if number of elements >= 4 then dynArray size is double, else 8
int init_cap = (size >= 4) ? 2 * size : 8;
// create pointer with enough space for struct and the actual array
dynArray *arr = (dynArray *) malloc(sizeof(dynArray) + init_cap );
arr->cap = init_cap;
arr->used = size;
// assign address of funciton copy to arr->cpy
arr->cpy = copy;
// call the function, to copy init_arr to arr->array
arr->cpy(arr->array, init_arr, size);
return arr;
}
void copy(int dest[], const int src[], int src_size) {
// just copy initial array to new array
int i;
memcpy(dest, src, src_size*sizeof(int));
/*
for (i=0; i<src_size; i++) {
dest[i] = src[i];
printf("%d\n", dest[i]);
}*/
}
So I call init_dynArray, sending a normal array and the number of elements in the array. init_dynArray uses malloc to create space in memory for the struct + the inintal size of the array, set up everything in the struct and copy the array, and then return a pointer to it. I don't get how it can only work some of the time. Hope yuo guys can help, thanks!
The problem in your code is on this line:
dynArray *arr = (dynArray *) malloc(sizeof(dynArray) + init_cap );
You need to multiply init_cap by sizeof(int)
dynArray *arr = (dynArray *) malloc(sizeof(dynArray) + sizeof(int)*init_cap );
You should also use size_t for the init_cap's type.
Note: Storing a pointer to the copying function inside the struct would be useful if your dynamic array consisted of opaque elements that require non-trivial copying. Since copying ints can be accomplished with a simple memcpy, there is no need to store a function pointer in dynArray.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int* create_int_array(){
int* arr;
arr = (int *)calloc(1,sizeof(int));
return arr;
}
char** create_string_array(){
char** arr = calloc(1,sizeof(char));
return arr;
}
void append_int(int* array, int element, int index){
array = (array+index);
*array = element;
}
void append_string(char** array , char* element,int index){
*(array + index) = calloc(1,sizeof(char*));
strcpy(*(array + index),element);
}
void delete_string(char** array, int index){
free(array[index]);
}
void delete_int(int* array,int index){
array[index] = NULL;
}
/////// M A I N F I L E ///////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "basic_data_file.h"
int main(int argc, char const *argv[])
{
/* code */
char **array;
array = create_string_array();
char *full_name = calloc(strlen("hamza arslan"),sizeof(char*));
strcpy(full_name,"hamza arslan");
char* mail = calloc(strlen("test#gmail.com"),sizeof(char*));
strcpy(mail,"test#gmail.com");
char* address = calloc(strlen("Hacettepe Universty"),sizeof(char*));
strcpy(address,"Hacettepe Universty");
char* statu = calloc(strlen("student"),sizeof(char*));
strcpy(statu,"student");
append_string(array,full_name,0);
append_string(array,mail,1);
append_string(array,address,2);
append_string(array,statu,4);
for(int i=0; i< 3; i++){
printf("%s\n",array[i]);
free(array[i]); // get free double pointer
}
printf("%s\n",array[4]); // because index 3 blow up
free(full_name);
free(mail);
free(address);
free(statu);
return 0;
}
I was try to own my basic array library . As you know else in some languages have high level array types. They are making easy our stocking operation. But in c, it's more complicated especially about string. I have 2 problem in here . First of all , when i give index=3 in append_string function , code blow up with Aborted(core dumped) error.(./run': double free or corruption (out)). Secondly , when i was checking leak memory ,it's get memory leak even i use free. What can i do?
Your create_xy_array functions allocate an array of 1 element, and they stay that way until the very end. When you have a one-element array and index, read/write its second and further elements, C itself happily approves, but the result will not work, it silently destroys everything in its path.
First of all, for having a dynamic array, you have to track its length yourself, C allocations/arrays do not know their own size. So you need a struct, containing the length and a pointer, something like
typedef struct IntArray {
int length;
int *elements;
} IntArray;
Then allocate it, for 0 elements, as there is nothing inside at the beginning:
IntArray* create_int_array() {
IntArray* ret = (IntArray*) malloc(sizeof(IntArray));
ret->length = 0;
ret->elements = NULL;
return ret;
}
void free_int_array(IntArray* arr) {
free(arr->elements);
free(arr);
}
Then you can try putting something inside:
void append_int(IntArray* arr, int element) {
arr->length++;
arr->elements = (int*) realloc(arr->elements, arr->length*sizeof(int));
arr->elements[length-1] = element;
}
(appending means adding something to the end of an array, there is no need for indices here)
And this could go on forever, deletion of an arbitrary element should shift the "upper" part of the array (memcpy) and resize the result to one element smaller or you could track the capacity of the array, which can be larger than its current length (but then it has to be incorporated into the append function and probably others).
(Disclaimer: I hope the snippet is correct, but I do not use C too often - and I can not suggest a good tutorial for the same reason, but that is what you probably need)
Note: I haven't code in C for years and I haven't check the code so double check and let me know.
Based on your description, you are trying to do a Vector.
Therefore, there are different ways that you can handle this.
Approach 1:
Create a structure which will hold the array, the capacity of the array, and the size of the array.
typedef struct StrArray{
int capacity;
int size;
int *integers;
}
The trick here is to take attention when you increase/decrease the capacity.
If you increase the capacity above the size of the array, then:
You need to create a new array with double the capacity
Copy all elements to the new array
Change pointer to new array
Free the memory of the old array
Approach 2
You can extend the previous approach by creating a function which returns a struct which holds the storage plus function pointers to the methods you wish to implement.
typedef struct StrStorage{
int capacity;
int size;
int *integers;
} StrStorage;
typedef struct StrArray {
StrStorage storage;
int (*capacity)(StrArray*);
int (*size)(StrArray*);
StrArray *(*append)(StrArray*, int);
void (*increaseStorage)(StrArray*);
// Add other methods here
} StrArray;
int capacity(StrArray *self) {
return self->storage->capacity;
}
int size(StrArray *self) {
return self->storage->size;
}
StrArray *append(StrArray *self, int integer){
if ((self->capacity() + 1) > self->size()){
self->increaseStorage();
}
// The rest of the magic goes here
return self;
}
StrArray *initializeStrArray(int n) {
StrArray* strArray = malloc(sizeof(StrArray));
strArray->chars = malloc(sizeof(char) * n);
strArray->capacity= capacity;
strArray->append = append;
return strArray;
}
Approach 3:
This approach is a continuation of the previous one.
In order to reduce the memory allocation, you can create an equivalent to a singleton which holds all the manipulation functions and then assi
There will be several crashes, but here is one:
char** arr = calloc(1,sizeof(char));
You are allocating 1 byte which is not sufficient to store a (char *), which needs between 2 and 8 bytes depending on the OS and target machine.
Try this instead:
char** arr = calloc(1,sizeof(char*));
You should double-check each line of code. C is not a forgiving language - mistakes are severely punished.
I have a struct called menu_item that looks like:
struct menu_item
{
char name[ITEM_NAME_LEN+1];
};
And in main I declare an array of pointers to the struct (am I right about this part?):
struct menu_item * menu_items[NUM_MENU_ITEMS];
And also in main I'm trying to call:
init_menu(&menu_items[NUM_MENU_ITEMS]);
init_menu function looks like this:
void menu_init(struct menu_item * menu_items[NUM_MENU_ITEMS])
{
/* allocate memory for each element in the array */
menu_items[NUM_MENU_ITEMS] = (struct menu_item *) malloc(sizeof(struct menu_item));
}
However I'm getting a segmentation error, what am I doing wrong? Thanks in advance.
Take a closer look to your function.
void menu_init(struct menu_item * menu_items[NUM_MENU_ITEMS])
{
/* allocate memory for each element in the array */
menu_items[NUM_MENU_ITEMS] = (struct menu_item *) malloc(sizeof(struct menu_item));
}
You need to carry the size of the array in a second parameter in your function. However, NUM_MENU_ITEMS, seems to be a global #define, thus you don't need to carry a second parameter.
Then you are accessing an out of bound cell, menu_items[NUM_MENU_ITEMS]. I assume you know that the indexing starts from 0 and ends at NUM_MENU_ITEMS-1.
In your function, you need, inside a loop, to allocate memory. Moreover, you don't need to cast what malloc returns.
So, for example, you could do something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ITEM_NAME_LEN 15
#define NUM_MENU_ITEMS 3
// Define the struct before main
struct menu_item {
char name[ITEM_NAME_LEN + 1];
};
// Give a synonym. Now struct menu_item is the same with menu_item_t.
// Notice the _t extension, which implies that this is a typedef.
typedef struct menu_item menu_item_t;
/**
* Given a pointer 'p' to an array of pointers
* (of type menu_item_t), allocate memory for
* every cell of the array.
*/
void init_menu(menu_item_t* p[]) {
int i;
for(i = 0; i < NUM_MENU_ITEMS; ++i) {
// for every cell of our array, allocate memory
p[i] = malloc(sizeof(menu_item_t));
// check that allocation for the i-th cell is OK
if(!p[i]) {
printf("Error in allocating %d item!\n\n", i);
return;
}
}
}
/**
* Given a pointer 'p' to an array of pointers
* (of type menu_item_t), de-allocate memory for
* every cell of the array.
*/
void delete_menu(menu_item_t* p[]) {
int i;
for(i = 0; i < NUM_MENU_ITEMS; ++i) {
// free the memory we had allocated for the i-th cell
free(p[i]);
// set the pointer to NULL
p[i] = NULL;
}
}
void fill(menu_item_t* p[]) {
int i;
for(i = 0; i < NUM_MENU_ITEMS; ++i) {
strcpy(p[i]->name, "myitem");
}
}
void print(menu_item_t* p[]) {
int i;
for(i = 0; i < NUM_MENU_ITEMS; ++i) {
printf("%s\n", p[i]->name);
}
}
int main(void) {
// Declare an array of pointers of menu_items_t.
// The size of the array is NUM_MENU_ITEMS
menu_item_t *menu_items[NUM_MENU_ITEMS];
init_menu(menu_items);
fill(menu_items);
print(menu_items);
delete_menu(menu_items);
return 0;
}
When I deal with structs, I always have this example on mind.
You are calling your function as
init_menu(&menu_items[NUM_MENU_ITEMS]);
This does not make sense. Expression &menu_items[NUM_MENU_ITEMS] creates a pointer to element with index NUM_MENU_ITEMS. Such element does not exist. Your array has elements numbered from 0 to NUM_MENU_ITEMS - 1. There's no element with index NUM_MENU_ITEMS.
Expression &menu_items[NUM_MENU_ITEMS] produces a pointer into the uncharted memory past the end of the array. You pass that pointer to the function. Later you are trying to use that pointer as if it were your array. You write into that uncharted memory, which causes a crash.
If you want to pass your array to the function, just pass it. Your function should be called as
init_menu(menu_items);
That's it. There's no need to create any pointers to any elements with strange indices.
Later, inside your function you are again trying to access element NUM_MENU_ITEMS of your array
menu_items[NUM_MENU_ITEMS] = ...
This does not make sense either for the very same reasons.
I have a structure called container that has two fields: labels and linked_to_containers; The field labels is designed to be a 2-dimensional array of int, and the field linked_to_containers is designed to be a 2-dimensional array of int pointers. On top of this, I also have an array of struct container that are dynamically created in the initiation program. I have the following code written down, but one thing I'm unsure about is the first malloc I used inside of the function container_init(). As the struct container still does not have its size initialized, is this the right way to do malloc for creating an array of struct container?
Please see my question in my comments in the code, and I will appreciate your feedback.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct container {
int *labels[2]; /* two-dimensional array of int */
int **linked_to_container[2]; /* two-dimensional array of pointers to label */
} container;
int get_next_container_index(int current_container_index, int max_index)
{
if (max_index - current_container_index >= 1)
{
return current_container_index + 1;
}
else
return 0; /* elements at two ends are linked */
}
container *allcontainers; /* an array for all containers */
void container_init(int num_containers, int column_num)
{
/* is this right to malloc memory on the array of container when the struct size is still unknown?*/
allcontainers = (container *) malloc(num_containers * sizeof(container));
int i;
for (i = 0; i < num_containers; i++)
{
container *current_container = &allcontainers[i];
current_container->labels[0] = malloc(column_num * sizeof(int));
current_container->labels[1] = malloc(column_num * sizeof(int));
current_container->linked_to_container[0] = malloc(column_num * sizeof(int *));
current_container->linked_to_container[1] = malloc(column_num * sizeof(int *));
int j;
for (j = 0; j < column_num; j++)
{
current_container->labels[0][j] = 0; /* initialize all labels to 0 */
current_container->labels[1][j] = 0;
int next_container = get_next_container_index(i, num_containers - 1); /* max index in all_containers[] is num_containers-1 */
current_container->linked_to_container[0][j] = &(allcontainers[next_container]->labels[0]);
}
}
The line in question seems perfectly fine to me, the size of struct container is well-known, because of its definition. The only size not known is the size of the arrays that the pointers in the struct will eventually point to, but that doesn't affect the size of the pointers themselves and thus also not the struct's size.
The only issue I see is here:
current_container->linked_to_container[0][j] = &(allcontainers[next_container]->labels[0]);
linked_to_container[0][j] is of type int*, but labels[0] is of type int* and therefore &(labels[0]) is of type int**. I am not sure what you try to accomplish here, but you probably need another index to labels[0][...] or & shouldn't be there.