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