c - i have got error reading dynamic string at the following code: -
i have got error string reading @ following code:
    #include <stdio.h>     #include <string.h>      main()  {  int = 0, j = 0,count=0;   char x,*str3;   char str2[50] = "nadir beton12345!";  (; x = str2[i] = str2[j]; j++)  {     if (x >= 'a' && x <= 'z' || x >= 'a' && x <= 'z')     {         count++;          i++;     } }          str3 = (char *)malloc((count * sizeof(char))+1);          printf("the new str without spaces , numbers is: \"%s\"\n", str3);          free(str3); }   i debug program , when debugger arrive dynamic allocation cant read string.
thanks.
i think problem not malloc, assignment:
char str2[50] = "nadir beton12345!";   this creates constant string located in read-only segment of process virtual memory.
str2[i] = str2[j]   cannot done.
you should allocate str3 before loop , update str3 as:
#include <stdio.h> #include <string.h> #include <malloc.h>  main()  {    int = 0, j = 0,count=0;     char x,*str3;     char str2[50] = "nadir beton12345!";     str3 = (char *)malloc((count * sizeof(char))+1);     (; (x = str3[i] = str2[j]) != '\0'; j++)    {       if (x >= 'a' && x <= 'z' || x >= 'a' && x <= 'z')       {         count++;          i++;       }    }     printf("the new str without spaces , numbers is: \"%s\"\n", str3);     free(str3); }   hope helped,
Comments
Post a Comment