I have a very simple program to print the chars in a string but for some reason it is not working:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void * print_chars(char *process_string) {
int i;
int string_len;
string_len = strlen(process_string);
printf("String is %s, and its length is %d", process_string, string_len);
for(i = 0; i < string_len; i++) {
printf(process_string[i]);
}
printf("\n");
}
int main(void) {
char *process_string;
process_string = "This is the parent process.";
print_chars(process_string);
return 0;
}
When I run it in Netbeans, I get the following:
RUN FAILED (exit value 1, total time: 98ms)
If I remove the line
printf(process_string[i]);
the program runs but nothing prints out to the console (obviously).
Any ideas what I’m missing here?
There are a couple of problems.
One is that you’re not seeing any output from the
printf("String is %s, and its length is %d", ...). This is because standard output is line buffered by default, and you are not including a newline, so it never actually decides that there’s a line ready to print. If you change the format string to add a\n, you will see the output from this command.The second is that you are passing a
charinto the first argument ofprintf(), where it expects achar *. This causes it to crash, as it tries to interpret that character as a pointer. You want to pass something likeprintf(process_string)instead. However, it’s generally a bad idea to pass a variable string directly into the first argument ofprintf(); instead, you should pass a format string that includes%s, and pass the string in as the corresponding argument:printf("%s\n", process_string). Or, if you want to print it character by character,printf("%c", process_string[i]), followed by aprintf("\n")to flush the buffer and actually see the output. Or if you’re doing it character by character,putchar(process_string[i])will be simpler thanprintf().