I am having a bunch of problems with pointers and dynamic arrays here.
I have a function that I call, that does a bunch a stuff, like removing an ellement from the dynamic array , which leads me to reallocating memory to one of those dynamic arrays. The problem is I call functions within functions, and I can't return all my values properly to the Main.
Since I can't return 2 values, how can I do this?
structure1* register(structure1 *registerArray,structure2 *waitingList, int counter){
//Bunch of code in here
registerArray = realloc(inspecao, (counter)+1);
waitingList = eliminate(waitingList, 5, counter); //Doesn't matter what it does really
return registerArray;
}
structure1* eliminate(structure1 *arrayToEliminateFrom, int positionToEliminate, int *counter){
//The code for this doesn't matter
//All I do is eliminate an ellement and reallocate it
arrayToEliminateFrom = realloc(arrayToEliminateFrom, (*counter-1)*sizeof(structure1))
return arrayToEliminateFrom;
}
As you can see , I don't know how to return the pointer to the waitingList dynamic array to the Main. How can I do this?
I have searched everywhere.
Help
Okay, here are two ways to do it.
The first is, based upon your comment, what you think your instructor would want:
void
xregister(structure1 **registerArray, int *arrayCount,
structure1 **waitingList, int *waitCount)
{
// Bunch of code in here
*arrayCount += 1;
*registerArray = realloc(inspecao, *arrayCount * sizeof(structure1));
// Doesn't matter what it does really
eliminate(waitingList, 5, waitCount)
}
void
eliminate(structure1 **arrayToEliminateFrom, int positionToEliminate,
int *count)
{
// The code for this doesn't matter
*count -= 1;
// All I do is eliminate an ellement and reallocate it
*arrayToEliminateFrom = realloc(*arrayToEliminateFrom,
*count * sizeof(structure1))
}
Here is what Roberto and I were suggesting. Actually, mine's a general variable length array approach that can be fully generalized with some slight field changes. In a way, since you're already using a struct, I can't see why your instructor would object to this as it's a standard way to do it. Less cumbersome and cleaner.
struct vector {
int vec_count;
structure1 *vec_base;
};
void
xregister(vector *registerArray,vector *waitingList)
{
// Bunch of code in here
registerArray->vec_count += 1;
registerArray->vec_base = realloc(registerArray->vec_base,
registerArray->vec_count * sizeof(structure1));
// Doesn't matter what it does really
eliminate(waitingList, 5)
}
void
eliminate(vector *arrayToEliminateFrom, int positionToEliminate)
{
// The code for this doesn't matter
arrayToEliminateFrom->vec_count -= 1;
// All I do is eliminate an ellement and reallocate it
arrayToEliminateFrom->vec_base = realloc(arrayToEliminateFrom->vec_base,
arrayToEliminateFrom->vec_count * sizeof(structure1))
}
Here's an even more compact way:
struct vector {
int vec_count;
structure1 *vec_base;
};
void
vecgrow(vector *vec,int inc)
{
vec->vec_count += inc;
vec->vec_base = realloc(vec->vec_base,vec->vec_count * sizeof(structure1));
}
void
xregister(vector *registerArray,vector *waitingList)
{
// Bunch of code in here
vecgrow(registerArray,1);
// Doesn't matter what it does really
eliminate(waitingList, 5)
}
void
eliminate(vector *arrayToEliminateFrom, int positionToEliminate)
{
// The code for this doesn't matter
vecgrow(arrayToEliminateFrom,-1);
}
you should try to do an higher structure that contains both pointers and pass and return that structure beetween your functions, because function can return only one object/structure, but your structure/object can contain more objects/structures
Related
In C++ we have structures which have a constructor and the destructor. It makes life much easier especially when it going to have the pointers, therefore dynamically allocated memory in the structure. You can even use std::shared_pointer library to deal with the pointers.
class A{
private:
int size;
double* stack;
public:
A(int size) : this->size(size){}
~A(){free(stack);}
};
But my maths lecturer doesn't like C++ and prefers everything in C. So I had to use C instead and came up with the following structure:
typedef struct vectorOfDoubles{
double* stack;
int size;
} vector;
I made up function that calculate the median of the vector of doubles.
double median_(const vector* v) {
vector n; // creates vector class object
n.stack = (double*)malloc(sizeof(double)*(n.size = v->size)); // takes double ptr and allocates the right amount of memory for it
memcpy(n.stack, v->stack, sizeof(double)*n.size); // copies the array of doubles.
sort(&n); // sorts the array of doubles
if(v->size%2) // checks for odd size
return n.stack[(v->size/2+1)]; // return median for odd size
else
return (n.stack[(v->size/2)]+n.stack[(v->size/2+1)])/2; // return median for even size
}
As an example of the bad practices I didn't free the memory. When the function returns its value it destructs the local variables and structures. But my structure has a pointer that holds the allocated memory. Unlikely after some research on the internet I didn't find any good destruction method solution for these situations.
My question is how the old-school C programmers dealt with those situations when they want to free the pointers in the structure but they do not have the destructor for structure that would execute itself to do a certain job?
A simple pointer needs a *alloc() and lastly a free().
A structure with dynamic fields deserves a crafted vector_alloc() and vector_free().
An old school flavored result:
// Return non-0 on error
int vector_alloc(vector *ptr, size_t size) {
assert(ptr);
ptr->stack = calloc(size, sizeof *(ptr->stack));
if (ptr->stack) {
ptr->size = size;
return 0;
}
ptr->size = 0;
return 1;
}
void vector_free(vector *ptr) {
assert(ptr);
free(ptr->stack);
ptr->stack = NULL;
ptr->size = 0;
}
double median_(const vector* v) {
vector n;
if (vector_alloc(&n, v->size)) return 0.0/0.0;
memcpy(n, v->stack, sizeof *n->stack *n.size);
sort(&n);
double y;
if(v->size%2)
y = n.stack[(v->size/2+1)];
else
y = (n.stack[(v->size/2)]+n.stack[(v->size/2+1)])/2;
vector_free(&n);
return y;
}
If you want to free an object that uses some kind of hierarchical storage (i.e., internal pointers to other object) in C, I usually write a free function specific to that object. For instance:
void free_my_obj(my_obj_t *my_obj)
{
free(my_obj->a);
free_my_obj2(my_obj->my_obj2);
free(my_obj);
}
At beginning: n.stack=…malloc();
At end: free(n.stack);
Every malloc() near beginning of block, should have a matching free(); near end of block.
I'm writing a parser for propositional logic (doesn't matter what that is, main point is I'm parsing a simple language) and initially started out with functions of the following form:
int formula() {
int store = step;
if(compound())
return TRUE;
else {
if(atom())
return TRUE;
else if(negation() && formula())
return TRUE;
else {
step = store;
return FALSE;
}
}
}
int compound() {
int store = step;
if(open() && formula() && binary_operator() && formula() && close())
return TRUE;
else {
step = store;
return FALSE;
}
}
The functions above not mentioned are base cases - these are the important parts. Formulas can have sub-formulas, and these sub-formulas in turn can be compound formulas, which contain sub-formulas, and so on.
Instead of ints though, I'm trying to return char sequences of 1s and 0s (true and false). If you return a sequence, it means that the input can generate a sequence (it must be valid). Otherwise, return null.
The issue is that every time I've tried the pointers keep getting lost - I understand this is to do with the stack(?) and the pointer sort of 'dies' when the function returns whatever. I've not tried arrays because I have been told that arrays work best statically, whereas the size of these arrays would be dynamic (size is determined by number of variables, which is only found at runtime).
Is there any way this approach can be done? I can't malloc anything because I won't be able to free it - the sequence of 1s and 0s needs to be returned before I'd be able to free it. Maybe pass structs with a sequence field, although I'm not sure if that suffers from the same issue.
Any help much appreciated. This is a program using C99. Any advice on clarifications welcome!
I'm not entirely following what you want to do, but there is not a clear reason why you couldn't use malloc. The pointer returned by malloc can be freed by another function later. Consider the following valid code:
char* foo(size_t* length)
{
*length = 3;
char* seq = malloc(*length);
seq[0] = 1;
seq[1] = 0;
seq[2] = 1;
return seq;
}
int main()
{
size_t length;
char* seq = foo(&length);
/* use seq */
free(seq);
}
You can also do it without malloc if you know an upper bound for your sequence. By passing a pointer to space you allocated on the stack from main(), you won't lose the data when the function exits:
void foo(char* seq, size_t total_size, size_t* used_size)
{
*used_size = 3;
seq[0] = 1;
seq[1] = 0;
seq[2] = 1;
}
int main()
{
size_t used_size;
char seq[100];
foo(seq, sizeof(seq), &used_size);
/* use seq */
}
I am working on generating all combinations from a code like ABCD for example, 24 combinations for this one 1 * 2 * 3 * 4.
I have this function:
static char *combi_switch(char *code, int i)
{
char *combi;
int j;
int k;
int l;
int s;
combi = (char *)malloc(sizeof(char) * ft_strlen(code) + 1);
ft_strcpy(combi, code);
k = i;
l = i;
j = ft_strlen(code) - 1;
if (i == j)
{
printf("%s\n", combi);
return (combi);
}
while (l <= j)
{
s = combi[i];
combi_switch(map, combi, k + 1, stock);
while (i < j)
{
combi[i] = combi[i + 1];
i++;
}
i = k;
combi[j] = s;
l++;
}
free(combi);
return (NULL);
}
ini called by this one:
char *combi_mix(char *code)
{
combi_switch(code, 0);
return (NULL);
}
ft_strlen && ft_strcpy are the same as the libc contains.
So with this functions if the code = "ABCD", printf illustrates the 24 combinations that are returned.
I went to stock all returns maybe in a char ** or a linked list.
is there a way to stock all those combinations that I printf?
is there a problem using "while" loops in recursive functions?
This is one of the last functions of my project so thank you so much if you can help me!
No, there's no any special problem with any kind of control construct in any kind of function. Use while or whatever. Now once we've got it out of the system, let's concentrate on the important question. How to accumulate the results of your function instead of printing them? It doesn't matter what the function actually computes, it's only important that it's recursive and each invocation prints something. We want to collect instead of printing.
First, a function should return something. Your current function returns a char* but it is never used. Your new function should return a value you are after, that is, a collection.
typedef struct {
/* whatever */
} string_collection;
We don't specify what sits inside of the collection. It might be a linked list, or a dynamic array together with its length, or whatever. You decide what kind of collection you want.
Now you need a couple of functions:
string_collection* create_empty_collection();
void add_element (string_collection* c, const char* s);
void move_elements (string_collection* c1,
string_collection* c2); // moves all elements from c2 to c1, leaving c2 empty
void destroy_collection (string_collection* c);
These functions modify their arguments. These are only example signatures. You may go for fully immutable interface if you wish:
string_collection* add_element (const string_collection* c, const char* s);
string_collection* concatenate (const string_collection* c1,
const string_collection* c2); //etc
In this variant, you create a brand new collection without touching existing ones. Each style has its place; use whatever works for you.
Now it's simple to modify the function:
string_collection* your_function (whatever parameters)
{
// First, need a collection to return
string_collection* coll = create_empty_collection();
// whatever
// whatever
// ATTN: old code was: printf ("%s", something), now do this:
add_elememt (coll, something);
// whatever
// whatever
// ATTN: old code was: your_function(whatever parameters), now do this:
string_collection* new_coll = your_function(whatever parameters);
move_elements (coll, new_coll);
destroy_collection (new_coll);
// whatever
// whatever
// ATTN: old code was: return something, now do this:
return coll;
}
When you call your function, you now do:
string_collection* coll = your_function (whatever parameters)'
// do something with the collection
destroy_collection (coll);
Here we have just learned to accumulate recursive function results. Awesome!
On a related note, your function mallocs a string each time it's called, but there's no free in sight. This is bad (a memory leak). Please add
free (combi);
where appropriate. In your case this means before any return statement. (It's a good practice to have a single return statement in the end of the function, instead of multiple statements scattered throughout the body; this is one reason for that).
you can simplify the program using below logic
char str[]="ABCD";
int i,j,k,l,count=0;
char temp;
l=strlen(str);
j=0;
k=1;
for(i=0;i<factorial(l);i++)
{
if(j==l)
{
j=0;
}
if(k==l)
{
k=0;
}
temp=str[j];
str[j]=str[k];
str[k]=temp;
printf("%s\n",str);
j++;
k++;
}
for more info you can see here
I am writing an huffman algorithm and I got problem with a collecting data in recursion function. It means I have a recursion function which generates codes from tree, but I would like to have them in array (this allow me processing data later). I wrote the function
void save_code(HuffNode** array, int pos, HuffNode *node, char * table, int depth)
{
if(node->left == NULL){
printf("%d - %c > ", pos, node->sign);
array[pos]->sign = node->sign;
strcpy(array[pos]->code, table);
puts(table);
// save to global table
}
else {
table[depth] = '0';
save_code(array, pos + 1, node->left, table, depth + 1);
table[depth] = '1';
save_code(array, pos + 1 , node->right, table, depth + 1);
}
}
The biggest problem I have with variable pos, I thought if I can increment the pos variable (like in loop for),so I would be able to save it in variable array at position pos. The whole program is here: https://github.com/mtczerwinski/algorithms/blob/master/huffman/huffman.c
Edit:
I ask myself if global variable can solve a problem - after a few moments of coding - the answer is positive.
int pos = 0; // global variable
void save_code(HuffNode** array, HuffNode *node, char * table, int depth) {
if(node->left == NULL){
array[pos]->sign = node->sign;
strcpy(array[pos]->code, table);
pos++;
}
else {
table[depth] = '0';
save_code(array , node->left, table, depth + 1);
table[depth] = '1';
save_code(array, node->right, table, depth + 1);
}
}
I would like to ask how to collect data in recursion function between calls. What are other ways to solve problem like this one.
Pass it by pointer:
void save_code(..., int *pos)
{
// ...
// use and modify (*pos) as you desire
// ...
save_code(..., pos);
// ...
}
This is a good approach, except that it doesn't look too pretty - you have an additional parameter for each recursive call and you have to use *pos instead of pos.
Pass and return it:
int save_code(..., int pos)
{
// ...
// use and modify pos as you desire
// ...
pos = save_code(..., pos);
// ...
return pos;
}
I wouldn't really recommend this (at least not above pass by pointer) as you'd return and pass a value, which seems unnecessary, since you only need to do one of those.
You also can't use this approach with multiple values, but it's easy to fix by using a struct, although if the function already returns something, this gets quite a bit messier.
And, for completeness, global variable:
int pos = 0; // global variable
void save_code(...)
{
// ...
// use and modify pos as you desire
// ...
save_code(...);
// ...
}
This has the disadvantage of having a pos variable floating around in global scope, but this could, in many cases, fairly easily be fixed by making it static so it's limited to one file, or, in the OOP world (e.g. in C++), one could hide this as a private class member.
Using a global variable would be a problem with multi-threading (i.e. multiple calls to the function executing at the same time).
I chose to favour brevity above completeness with regard to my code samples - I hope they're readable enough.
I want to write a recursive function that builds up all possible solutions to a problem. I was thinking that I should pass an array and then, in each recursive step, set it to all values possible in that recursive step, but then I started wondering if this was possible, since C passes an array by passing a pointer. How do you typically deal with this?
I'm thinking something along these lines. The array will take many different values depending on what path is chosen. What we really would want is passing the array by value, I guess.
recFunc(int* array, int recursiveStep) {
for (int i = 0; i < a; i++) {
if (stopCondition) {
doSomething;
}
else if (condition) {
array[recursiveStep] = i;
recFunc(array, recursiveStep+1);
}
}
}
You can pass an array by value by sticking it into a struct:
struct foo { int a[10]; };
void recurse(struct foo f)
{
f.a[1] *= 2;
recurse(f); /* makes a copy */
}
If you need pass by value, you could always wrap your array into a structure and pass that. Keep in mind that your now struct contained array still needs to be big enough to handle all cases.
Wrap it in a struct.
typedef struct arr_wrp {
int arr[128]; // whatever
} arr_wrp;
void recFunc(arr_wrp arr, int step) {
// do stuff, then
arr.arr[step] = i;
recFunc(arr, step + 1);
}