I've hit a roadblock, when trying to manipulate strings when "storing" them as pointer variables.
// Sample code to input a string till line break is encountered, later re-allocating to save space
char *s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
// Code to replace whitespaces with newlines
for (char *c = s; *c != '\0'; c++) {
if (*c == ' ') {
*c = '\n';
}
}
printf("%s", s);
I want an explanation of char *c = s in the above code snippet, because when I tried to use the same concept to iterate over the string characters in another example (below) I was greeted with Segmentation fault runtime error.
I want to find the frequency of digits (0 to 9) from a string entered by the user:
int count[10];
char *s = malloc(1024 * sizeof(char));
scanf("%[^\n]", &s);
s = realloc(s, strlen(s) + 1);
for(char *c = s; *c != '\0'; c++) { // Shows Segementation fault here
if(*c >= '0' && *c <= '9') {
count[*c - '0'] += 1; // I am still trying to work this
}
}
countis uninitialized. This is one problem. The other is already answered down there...mallocfollowed byrealloc? And by the ways = realloc(s, ...)is an anti-pattern. Ifreallocfails you lose your original pointer and leak memory.