I have this code, and I want from a string that is stored in value called original such as home$family$fun, using the delimiter value such as $, assign to another string named final the word between the two delimiters. That means that final should contain family and print the result from main. But the operation must be done in another function using only pointer and pointer arithmetic. Also the prototype of the getPart function must not be changed.
My problem is that, I get this result to my variable final when I am inside the getPart function but when I am returning to main the final function have only '\0' as value and not the value I wanted it. I think, the problem is something with the addresses, meaning that if the value which string's address change, then the value of string will be changed. But I am a bit confused...Could someone help me?
#include <stdio.h>
#include <string.h>
#define SIZE 32
int getPart(char original[], char delimiter[], char final[]) {
int i, j;
int counter = 0;
int counter1 = 0;
for(i = 0; *(original + i) != '\0'; i++) {
if(*(original + i) == *delimiter) {
counter++;
}
}
if(counter > 1) {
for(i = 0; *(original + i) != '\0'; i++) {
if(*(original + i) == *delimiter) {
if(counter1 < 1) {
final = (original + i + 1);
counter1++;
}
else {
for(j = 0; *(final + j) != '\0'; j++) {
if(strcmp(final + j,original + i) == 0) {
*(final + j) = '\0';
*(final + j + 1) = '\0';
//final + j = '\0';
}
}
}
}
}
return(1);
}
else {
return(0);
}
}
int main(int argc, char *argv[]) {
char original[SIZE], delimiter[SIZE], final[SIZE];
char format_str_or[20], format_str_del[20];
int counter, i;
for(i = 0; i < SIZE; i++) {
*(final + i) = '\0';
}
sprintf(format_str_or," %%%ds",SIZE - 1);
printf("Enter string: ");
scanf(format_str_or,original);
sprintf(format_str_del," %%%ds", SIZE - 1);
printf("Enter delimiter: ");
scanf(format_str_del,delimiter);
counter = getPart(original,delimiter,final);
printf("%d\n",counter);
if(counter == 1) {
printf("%s\n",final);
}
else if(counter == 0) {
printf("%s does not appear twice in %s\n",delimiter,original);
}
return(0);
}