Reputation: 1
For the below question,
Write a function
replace
which takes a pointer to a string as a parameter, which replaces all spaces in that string by minus signs, and delivers the number of spaces it replaced.Thus
char *cat = "The cat sat"; n = replace( cat );
should set
cat to "The-cat-sat"
and
n to 2.
In the above problem, char *cat="That cat sat"
is nothing but const char *cat="That cat sat"
Here is my non-working code for this problem,
#include<stdio.h>
int replace(char[]);
int main(void){
const char *cat = "The cat sat";
int n = replace((char[])cat);
printf("\n Now the output is: \"%s\"", cat);
printf("n is %d", n);
}
int replace(char cat[]){
int count =0;
for(int i =0; cat[i] != '\0'; i++){
if(cat[i] == ' ') {
cat[i] = '-';
count++;
}
}
return count;
}
To analyse this code,
const char *cat
is pointing to a buffer(The cat sat
) that cannot be modified.
So, am casting((char[])
) to make cat
a (non-const)modifiable buffer, before calling replace((char[])cat)
. Because, C is loosely typed
But the program still segments at cat[i]='-'
How do I understand this problem?
Upvotes: 0
Views: 5785
Reputation: 36
Strings inside "" are called string literals. These are immutable. So, instead of
const char *cat = "The cat sat";
You can write:
char cat[20]; // This or calloc/malloc. Your choice
strcpy(cat, "The cat sat");
And then pass this in to the function.
Upvotes: 1
Reputation: 19333
I cover this question at great length in this question:
Difference between declared string and allocated string.
In short, the manner in which you declare the string, regardless of the const
storage class modifier, is stored in RODATA (ie: text segment), so re-casting it to non-const
(something you should try to avoid, since there are few legitimate reasons for doing this) doesn't help you.
In c, if you want to make a buffer selectively-writable, hide it away in a context variable or as a static variable within a source file, and only allow access to it via private API calls (ie: "getter"/"setter" functions).
Upvotes: 1