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);
}
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);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments