'I want to censor a word to asterisks based on the original length(Happy to *****, dog to *** for example) and my current code doesn't work. Any ideas?
Attempt at censoring "hello" to "*****" The error message it gives is signal: segmentation fault (core dumped).
#include <stdio.h>
#include <string.h>
int main(void) {
char word = "hello";
int i;
int len = strlen(word);
char modified[len];
for(i=0; i<len; i++){
modified[i] = "*";
}
printf("%s",modified);
}
Solution 1:[1]
There are a few things wrong here.
First, char is not a string, it's a single character, which is essentially a short, single byte integer. The line char word = "hello"; takes the address of the string "hello", converts it to an integer, and assigns that integer to word. You don't actually want the numeric representation of the strings address, you want a pointer to the actual string, so your word should be a const char*, not a char.
Secondly, you don't reserve enough space for a null byte at the end of your string. Strings in C are simply sequences of characters, terminated by a null byte, and you're expected to add a null byte to your string so functions that use strings know when the string stops.
Thirdly, you're assigning the string "*" to each character in your modified array. A string is not a character, character literals are delimited with single quotes: '*'.
All in all, you can correct the issues and wind up with something like this:
#include <stdio.h>
#include <string.h>
int main(void) {
const char *word = "hello";
int i;
int len = strlen(word);
char modified[len + 1];
for(i=0; i<len; i++){
modified[i] = '*';
}
modified[len] = 0;
printf("%s",modified);
}
Solution 2:[2]
You mix up char and strings "*" and '*' are very different thing in C.
Declare a const string:
const char* word = "hello";
set a char:
modified[i] = '*';
String is null terminated => modified[len] = '\0';
add a \n to printf to have a line break
Add return 0;
as expected for main.
#include <stdio.h>
#include <string.h>
int main(void) {
const char* word = "hello";
int i;
int len = strlen(word);
char modified[len + 1];
for(i=0; i<len; i++){
modified[i] = '*';
}
modified[len] = '\0';
printf("%s\n",modified);
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user229044 |
| Solution 2 |
