Friday, 15 February 2013

iphone - Remove chars from one string which are present in another string -



iphone - Remove chars from one string which are present in another string -

this code remove characters 1 string, p, there in other string, s, , concatenate 2 strings , print final string.

for ex: if inputs are

stringp= "hello" strings= "fellow"

output: hfellow

another ex

input stringp= "android" strings= "google"

output

andridgoogle

the comparing of characters case sensitive.

currently getting segmentation fault after entering first string. can please help me in correcting code? , why segmentation fault occurs, in scenarios occurs?

thanks in advance.

#include <stdio.h> #include<string.h> void remove_char(int *len, char *string1); int main() { char *p,*s,*t; int len1,len2,i,j; printf("enter 2 strings\n"); scanf("%s",p); scanf("%s",s); len1=strlen(p); len2=strlen(s); for(i=0;i<len1;i++) { for(j=0;j<len2;j++) { if(*p==*(s+j)) { remove_char(&len1,p); } if(*p=='\0'||*(s+j)=='\0') { break; } } p++; } strcat(p,s); strcat(t,p); printf("%s",t); homecoming 0; } void remove_char(int *len, char* string1) { int a; for(a=0;a<*len;a++) { *string1=*(string1+1); string1++; } len--; }

the declaration char* p says p variable contains address of character (or potentially address of character array).

in code, create storage space character (or array). think of was, p alias location in local stack frame (say four-byte area), , it's contents interpreted address in heap.

now, no in code allocate memory, need this:

p = malloc(15*sizeof(char));

this assuming want user come in string of no more 14 characters (don't forget null-terminator). p contains address of area on heap can used store characters.

so, reply question, getting segmentation fault after entering first string because failed allocate memory store string in.

also, note scanf insecure in take string long user feels typing in , result in heap-based buffer overflow. if want read in string of @ 14 character, seek this;

#define str_len 14 char* p = malloc(str_len*sizeof(char)); scanf("%str_lens", p);

notice have set length in specifier scanf limit reading in @ str_len characters. help prevent over-flows, not exclusively prevent it.

iphone c string pointers

No comments:

Post a Comment