0
//Generating all possible binary strings of lenght 'n' 
#include<stdio.h>
#include<stdlib.h>
char a[20];
int ind = 0;
void generateAllBinaryStrings(int n, char **arr,int `i){
 if (i == n){
    printf("%s  \n",a);
    arr[ind] = a;
    ind++;
    return ;
} 

a[i] = '0';
generateAllBinaryStrings(n, arr, i+1); 

a[i] = '1';
generateAllBinaryStrings(n, arr, i+1) ; 

 }

int main(){
 int n = 3,k;   
 char *arr[8];
 generateAllBinaryStrings(n, arr, 0);
 printf("\n");
 for(k=0;k<8;k++)
    printf("%s\n",arr[k]);
return 0;
}

// Why this code giving weird output? //How to return the array of pointers values updated in another function to main()???

//What's wrong with this code?

//output:

cherrycharan@cherrycharan-HP-Notebook:~/Desktop$ ./a.out
 // In generateAllBinaryStrings()
 000  
 001   
 010  
 011  
 100  
 101  
 110  
 111  

 // In main()
 111
 111
 111
 111
 111
 111
 111
 111

// Why this code is giving weird output? //How to return the array of pointers values updated in another function to main()???

//What's wrong with this code?

  • The question is rather what you are trying to do and where you allocate memory for the strings. The code posted doesn't make sense on it's own. – Lundin Jun 10 '19 at 08:29

1 Answers1

1

Since you are doing pointer assignment, pointers in arr will be always pointing to updated contents of a that is 111.

arr[ind] = a;

Copy the contents instead.

arr[ind] = strdup(a);

And make sure you free afterwards.

kiran Biradar
  • 12,700
  • 3
  • 19
  • 44