Pass array by value to recursive function possible? - c

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

Related

Returning Two Pointers to Dynamic Arrays

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

Using an array as input in a recursive method in C

I am having a problem with using an array as input within a recursive function here is the problem: i set the array values to what i want in the first level of recursion , but the changes that are made to an array in level 2-3 of the recursion somehow change the array of the level 1 of recursion. This should not happen right? because everytime the method is recalled it should store the particular array for what it has been called right?
here is the code of the recursive method the method is called vertexCover:
int vertexCover (int start, int covering, int seen [1000]){
if(covering==0){
if(start>numberOfEdges-1){
return 1;
}
else{
while(start<=numberOfEdges-1){
if(seen[edge1[start]]==0 && seen[edge2[start]]==0){
return 0;
}
start++;
}
return 1;
}
}
else{
while(seen[edge1[start]]!=0 || seen[edge2[start]] !=0){
start++;
if(start>numberOfEdges-1){
return 1;
}
}
seen[edge1[start]]=1;
int a= vertexCover(start + 1, covering-1, seen);
seen[edge1[start]]=0;
seen[edge2[start]]=1;
int b = vertexCover(start+1,covering-1,seen);
if(a==1 || b==1){
return 1;
}
else {
return 0;
}
}
}
What I want to do is to make sure each call to the recursive method has its own unique array, changes made to the array not affecting the array stored from the previous call. For some reason it is not doing this.
if you really want to do it you will need to copy you array like that.
int vertexCover (int start, int covering, const int array [1000]){
int seen[1000];
memcpy(seen, array, sizeof(seen));
...
}
but your program will be very slow if you do that so I think you should use short array or find another way to do what you want.
Your function:
int vertexCover(int start, int covering, int seen [1000]) { ... }
Is treated identically to:
int vertexCover(int start, int covering, int *seen) { ... }
So changes made to seen[0] will be visible to all users of that pointer. If you want a local copy of the array, you'll need to explicitly make a copy of it.

How can I Return an array from a function without using malloc?

I've been struggling with a simple task in C... (It's been a while.) I need to build a function that creates and resets an array of structs without using any memory allocation functions.
I originally designed it with malloc:
typedef struct {
int ..
int ..
} Branch;
Branch* createBranchList (int N)
{
Branch *List;
Branch reSet = {0}; // a zero'd Branch struct used for the resetting process
int i;
if(!(List=(Branch*)malloc(sizeof(Branch)*N))){
printf("Allocation error");
return NULL;
}
for(i=0; i<N; i++)
List[i] = reSet;
return List;
}
Now how can I do this without using memory allocation? Can I return a reference? I don't think so.
Thanks anyone for helping out.
Safe method (1):
Define a struct with an array member, then return that.
e.g.:
struct MyContainer {
Thing x[42];
};
MyContainer foo(void) {
MyContainer m;
m.x[0] = 5;
m.x[1] = 10;
...
return m;
}
Obviously, this method will not be possible if the array size is not known to the function at compile-time.
Safe method (2):
Have the caller pass in the array as an argument.
e.g.:
foo(Thing *things, int N) {
thing[0] = 5;
thing[1] = 10;
...
}
Unsafe method:
Declare a static local array, and return a pointer to that.
This "works" because a static array is not deallocated when it goes out of scope. But it's unsafe because the array will be overwritten next time you use the function (particularly bad in a multi-threaded scenario).
This method will also not be possible if the array size is not known to the function at compile-time.

Send dynamic array to function C++

I have an array, which is now static. This are the operations I do with it.
Firstly I create a two-dimensional array. Then I fill it in, using cycles. And then I send it to function, where there are also cycles which are used.
Here I 'd like to post some sample code, which is similar to mine.
bool picture[20][20]; //here's my array right now. Pretty ugly. Just for testing.
for (int y=0;y<Height;y++)
{
for (int x=0;x<Width;x++)
{
if (treshold<middle)
{
picture[x][y]=1;
}
else
{
picture[x][y]=0;
}
}
}
//Here's an example of filling an array
leftk = left(picture,widthk, heightk); //That's how I use a function
int left(int picture[200][200],int row,int col)
{
for (int x = 0; x <=row-1; x++)
{
for (int y = 0; y <=col-1 ;y++)
{
if (picture1[x][y]==1)
{
return x;
}
}
}
}
//And that's the function itself
So here I need to switch my array to a dynamic one. That's how I declare my dynamic array
bool** picture=new bool*[size];
for(int i = 0; i < size; ++i)
picture[i] = new bool[size];
//size is just a variable.
As for statically declared cycles, everything is very simple. Sending this array as a parameter to function.
I've already managed to create a dynamic array, it's simple. Then I fill it in with numbers. No problems here too. But I can't understand, how to send an array to function and moreover how to use it there.
Could you give me an exaple of modifying two-dimensional arrays in functions.
Sorry for such a newbie question. Hope someone will help.
By the way, class wrapping would be a bit confusing here, I think.
A function such as:
Process2DArray(int **pArray, int rowCount, int colCount)
Should suffice the needs assuming its a 2D array that is being operated on. Also, consider using std::vector<std::vector<int>> instead of a multidimensional array allocated manually. This approach will help prevent leaks. The second approach also lets you have jagged arrays.
The usual solution is to wrap the array in a class; C doesn't handle
arrays very well, and C++ doesn't have any real support for 2D arrays in
its library either. So you define either:
class Array2D
{
std::vector<double> myData;
int myColumnCount;
int myRowCound;
// ...
};
with accessors which convert the two indexes using i * myColumnCount +
j, or:
class Array2D
{
std::vector<std::vector<double> > myData;
// ...
};
with initialization logic ensure that all of the rows have the same
length. The first is generally simpler and easier to understand; if you
want to increase the number of columns, however, the second is
significantly easier.
You have several options:
an array of arrays. For example, for int would be int **a which should be able to hold n arrays new int *[n], then go with a for through them and initialized them a[i] = new int[elems_per_line]
a "packed" 1D array int *a = new int[n * elems_per_line], where element (i, j) - 0-based is actually a[i * elems_per_line + j].
you can refine point 1, and have the 2D matrix be "curly" - with lines of different lengths, but you'll need an array to hold each length.
Hope this helps.

Functions and returning values in C

Im trying to print out the part at the end of this program. I enter C17 and the part comes out as 0 when it should be 1. Why is this?
Kind Regards
Dennis
# include <stdio.h>
int Part;
int getPartType(int Part);
int calcPrice(int Part);
int main(int argc, char * argv[]){
getPartType(Part);
calcPrice(Part);
return 0;
}
// Part1: Asks for input from user for part type
int getPartType(int Part) {
int nvr;
char character_one;
char character_two;
int number;
printf("Enter the part type (C17, F25, DN3, GG7 or MV4): ");
nvr = scanf("%c%c%d",&character_one,&character_two,&number);
if (number==7 && character_two=='1') {
Part=1;
}else if (number==5 && character_two=='2') {
Part=2;
}else if (number==3 && character_two=='N') {
Part=3;
}else if (number==7 && character_two=='G') {
Part=4;
}else if (number==4 && character_two=='V') {
Part=5;
}else{
printf("Wrong Part Type\n");
Part=0;
}
return Part;
}
int calcPrice(int Part) {
printf("%d\n",Part);
return 0;
}
getPartType(Part); returns an int, and doesn't assign to the original Part. So you must change this line:
getPartType(Part);
to
Part = getPartType(Part);
If you want to change the original value of Part you must use pointers. You can read more about this in any decent C book (I recommend K&R). For example:
// takes pointer to integer and sets it to 5
void settofive(int *someInteger) {
*someInteger = 5; // dereference someInteger and set to 5
}
int main(int argc, char *argv[]) {
int test = 0;
int *ptrTotest = &test; // take address of test and store in ptrTotest
printf("%d\n", test); // prints out zero
settofive(ptrTotest);
printf("%d\n", test); // prints out five
return 0;
}
You have a little misunderstanding of function argument passing.
When you call a function like
getPartType(Part);
C will create a copy of Part on the stack and all computations within the function will be made on this copy. Therefore you will not change the variable Part. This is called Call-by-value.
To change this problem, there are two ways. You can either just use:
Part = getPartType(Part);
This will create a copy of Part, the function will work on this copy, and then return something. This something will then get stored in the original Part. In your case you can actually just use int getPartType(void) as the function declaration, because you don't work an Part.
The other way would be to pass a pointer:
getPartType(&Part);
This passes a pointer to the original Part, so you can manipulate the original part (using the *-operator). This would mean that your declaration shoudl like like void getPartType(int *). But I would say the first method is preferable if you are dealing with just one basic variable
C is call by value. This means that the function can't change the value of a variable in the caller's context, unless the caller passes the address of that value.
Since your function doesn't really need an input argument, it should be removed. All you need is the return value.
Also, you could consider using multiple return statements, changing the if-ladder to look like so:
if (number==7 && character_two=='1') {
return 1;
}else if (number==5 && character_two=='2') {
return 2;
and so on.
Further, the use of "magical" numerical constants is generally a bad idea. It would be better to introduce an enumeration before main(), like this:
enum Part { PART_C17 = 1, PART_F25, PART_DN3, PART_GG7, PART_MV4 };
Then change the function to return a value of this new type:
enum Part getPartType(void)
{
/* ... */
}
and update the code in the if-ladder accordingly:
if (number==7 && character_two=='1') {
return PART_C17;
}else if (number==5 && character_two=='2') {
return PART_F25;
and so on.

Resources