c - Segmentation fault on strcat -


i have begun working on learning c language , have repeatedly run error in calling strcat function <string.h> module results in segmentation fault. i've searched answers online, including on this stackoverflow post, without success. thought community might have more personal insight problem, general solutions don't seem working. might user error, might personal issue code. take look.

#include <stdio.h> #include <string.h>  char * deblank(const char str[]){     char *new[strlen(str)];     char *buffer = malloc(strlen(new)+1);     (int i=0; i<strlen(*str); i++){         if(buffer!=null){             if(str[i]!=" "){                 strcat(new,str[i]); //segmentation fault             }         }     }     free(buffer);     return new; }  int main(void){     char str[] = "this has spaces in it.";     char new[strlen(str)];     *new = deblank(str);     puts(new); } 

i've placed comment on line i've traced segmentation fault to. following java make sense out of c code.

public class deblank {     public static void main(string[]args){         string str = "this has space in it.";         system.out.println(removeblanks(str));     }      public static string removeblanks(string str){         string updated = "";         for(int i=0; i<str.length(); i++){             if(str.charat(i)!=' '){                 updated+=str.charat(i);             }         }         return updated;     } } 

any insights error appreciated. please point out typos well... i've been known make them. thanks.

you can't use strcat did, intended catenate c-string @ end of given one. str[i] char not c-string (remember c-string contiguous sequence of chars last being nul byte).

you cannot compare strings standard comparison operators, if need compare strings there strcmp function it. can compare chars standard operators char kind of integer type.

this should trick:

#include <stdio.h> #include <string.h> #include <stdlib.h>  char * deblank(const char str[]) {     char *buffer = malloc(strlen(str)+1); // allocate space contains char in str, included ending nul byte     (int i=0, j=0; i<strlen(str)+1; i++) { // every char in str, included ending nul byte       if (str[i]!=' ') { // if not blank         buffer[j++] = str[i]; // copy       }     }     return buffer; // return newly constructed c-string }  int main(void){     char str[] = "this has spaces in it.";     char *new = deblank(str);     puts(new);     free(new); // release allocated memory } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -