Reputation: 115
I'm trying to write a function that takes in a const char*
and iterates through it until it matches the first character of the const char* hello
. It then prints the amount of characters it had to advance and the mth
character. As of now, I have gotten it to point to where I want to, but I can't seem to access it
const char* hello = "hello";
const char* no_bears = "ERROR: Message must contain 'THIS IS BEAR TERRITORY!' yeeee";
int is_commit_msg_ok(const char* msg) {
/* COMPLETE THE REST */
int m = 0;
char* message = &msg[0];
while (message[m] != hello[0]) {
if (message[m] == '\0') {
return 0;
}
m++;
}
printf("%d\n",m );
printf("%s\n", message[m]); \\ causes segmentation fault
When I do message[m], however, I get a segementation fault: 11 error, and I don't really know how to fix this...
Upvotes: 0
Views: 3660
Reputation:
You can use printf("%c\n", message[m]);
because you printing just single char not a string with "%s".
Upvotes: 1
Reputation: 98348
In this line:
printf("%s\n", message[m]);
message
is of type char*
so message[m]
is of type char
but %s
expects a char*
.
Passing the wrong type to printf()
is undefined behaviour. But what it probably does is to interpret the char
value as a pointer and try to read the memory there. Since it is not a valid pointer, it segmentation-faults.
Solution, use %c
, that prints a char
.
printf("%c\n", message[m]);
Many modern compilers will warn you about these kind of errors if you enable the warnings. For example in GCC/Clang, you should really use -Wall
.
Upvotes: 3