I have error with c function -
i new c, try write code , need deal string. need cut first word string, , need return the word , rest of string.
i wrote code cut first word getting error "segmentation fault (core dumped)" know why, how fix it? symbol equal " ".
char * cut(char *str, char *symbol) { int i=0; static char *temp; while (str[i]!=symbol[0]) { temp[i]=str[i]; i++; } printf("temp %s\n ",temp); return temp; }
the posted code contains few problems. including undefined behaviour.
caveat: code assumes parameter str points nul terminated string.
#include <stdio.h> // printf() #include <stdlib.h> // exit(), exit_failure #include <string.h> // strlen(), malloc() char * cut(char *str, char *symbol) { char *temp = null; if( null == (temp = malloc( strlen(str)+1) ) ) { // malloc failed perror( "malloc failed" ); exit( exit_failure ); } // implied else, malloc successful int i; for(i=0; str[i] && str[i] !=symbol[0]; i++) { temp[i]=str[i]; } // terminate string temp[i] = '\n'; printf("temp %s\n",temp); return temp; } however, question says return first word , rest of string neither posted code nor answer implement
Comments
Post a Comment