Returning char pointer from function prints empty
i have two different programs that are very similar. The first one just
takes in an argument from the command line(so it stores it in argv). I
copy the string with strcpy into a pointer that was malloc'd and then pass
it to my function where it takes the characters one at a time from where
the pointer is pointing to another pointer where space was also malloc'd.
I return the result and print it. If my input is hii the output is hii. My
second program is very similar, it takes two arguments this time and we
copy each into two separate pointers that were malloc'd and then pass it
to my function. This time we only copy over characters that match from one
char pointer to the other one. Whatever matches we add it into the same
pointer that was malloc'd as we did with the first program. The problem is
when i return the pointer and have the resulted string printed i get a
blank line. So input would be hi fjdhddif and output is an empty line.
Programs:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct StructHolder {
char *words;
};
typedef struct StructHolder Holder;
char *GetCharacters(Holder *ptr){
int i=0;
char *words=malloc(sizeof(char));
for(i;i<strlen(ptr->words);i++){
words[i]=ptr->words[i];
words=realloc(words,sizeof(char)+i);
}
words[strlen(ptr->words)]='\0';
return words;
}
int main(int argc, char **argv){
Holder *structptr=malloc(sizeof(Holder));
structptr->words=malloc(strlen(argv[1]));
strcpy(structptr->words, argv[1]);
char *charptr;
charptr=(GetCharacters(structptr));
printf("%s\n", charptr);
return 0;
}
Program 2:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct StructHolder {
char *wordsA;
char *wordsB;
};
typedef struct StructHolder Holder
char *GetCharacters(Holder *ptr){
int i, j, c=0, f2;
char *words=malloc(sizeof(char));
for(i;i<strlen(ptr->wordsA);i++){
f2=0;
for(j=0;j<strlen(ptr->wordsB) && f2==0;j++){
if(ptr->wordsA[i]==ptr->wordsB[j]){
printf("both match\n");
f2=1; //just exits the loop so that we don't go through
the rest checking`
printf("adding\n");
words[c]=ptr->wordsB[j];
c++;
words=realloc(words,sizeof(char)+i);`
}
}
}
words[strlen(ptr->wordsA)]='\0';
return words;
}
int main(int argc, char **argv){
Holder *structptr=malloc(sizeof(Holder));
structptr->words=malloc(strlen(argv[1]));
strcpy(structptr->wordsB, argv[1]);
strcpy(structptr->wordsA, argv[2]);
char *charptr;
charptr=(GetCharacters(structptr));
printf("%s\n", charptr);
return 0;
}
No comments:
Post a Comment