c - String manipulation code using char ** pointer gives unexpected result -
i trying implement string parsing code need substring of given string deed following:
the header file : test.h
#ifndef header_file #define header_file #include<stdio.h> #include<string.h> int increment(char **); #endif
the source files : main.c test.c
test.c :
case1 :test.c
#include"test.h"
int increment(char **string){
char *temp = *(string); int value; if(temp != null){ *(string) = ++temp; value = 1; } else{ value = 0; } return value;
}
case2 :test.c
#include"test.h"
int increment(char **string){
char *temp = *(string); int value; if(*temp != '\0'){ *(string) = ++temp; value = 1; } else{ value = 0; } return value;
}
main.c:
#include"test.h" int main() { char str[30] = "i have done form here comes."; char strs[50]; char *p = str; memset(strs, 0, 50); while(increment(&p)) { strcpy(strs,p); printf("originally string : %s\n", str); printf("the modified string : %s\n", strs); memset(strs, 0, 50); } return 0; }
the makefile :
#this makefile. : run main.o test.o run : main.o test.o $(cc) -g $^ -o $@ %.o : %.c $(cc) -g -c $^ -o $@ .phony : clean clean : -rm -f *.o run
but in first case in test.c tried traversed sub-string giving garbage result. , second case works fine.
what going wrong in test.c case 1.
thanks!!!!!!!!!!!!
the purpose add prefix , suffix every word in string need string before word , word , , after word. ex: prefix_i_suffix have done form here comes. prefix_have_suffix have done form here comes.
you're doing few things wrong.
- i don't see splitting words spaces anywhere @ all, , seems main requirement.
- i see, however, insane operations on pointers. frankly, can't understand logic behind them.
so let me give examples how can done - without modifying pointers @ all:
#include <stdio.h> #include <string.h> int main () { char str[] = "i have done answer here comes."; const char *delimiters = " "; char *pch = strtok(str, delimiters); while (pch != null) { printf("prefix_%s_suffix\n", pch); pch = strtok(null, delimiters); } return 0; }
with copying input intermediate array can modify want:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main () { char str[] = "i have done answer here comes."; char **array = null; size_t array_size = 0; const char *delimiters = " "; char *pch = strtok(str, delimiters); while (pch != null) { size_t str_size = strlen(pch) + 1; //to accommodate `\0` byte char *str_copy = malloc(str_size); if (!str_copy) { printf("no memory!"); return 1; } memcpy(str_copy, pch, str_size); ++ array_size; array = realloc(array, sizeof(char*) * array_size); if (!array) { printf("no memory!"); return 1; } array[array_size - 1] = str_copy; pch = strtok(null, delimiters); } (size_t = 0; < array_size; ++) { printf("prefix_%s_suffix\n", array[i]); free(array[i]); } free(array); return 0; }
Comments
Post a Comment