I was just trying to test if I installed a new ide correctly and tried to compile this basic program, both in the IDE and with gedit and GCC and it would compile, but crash after I launch the executable in the command line – I have no idea what’s wrong, as I’m still fairly new to pointers in C and it takes a while to wrap your head around the theory, according to most people.
Code:
#include <stdio.h>
#include <string.h>
char print_func(char *hi);
int main(void) {
char *hi = "Hello, World!";
print_func(*hi);
}
char print_func(char *hi) {
printf("%d \n", *hi);
}
I tried this:
#include <stdio.h>
#include <string.h>
char print_func(char *hi);
int main(void) {
char *hi = "Hello, World!";
print_func(&hi);
}
char print_func(char *hi) {
printf("%d \n", *hi);
}
and it outputs 44 with no crash.
If you do indirection using,
print_func(*hi);you are passing a char and it is one byte. So when you are trying to read an integer, which is larger, an access violation occurs. You should call your function with a pointerprint_func(hi). And if you want to print the address of a string, it is better to use%pin printf:If you want to print the first character in hi, use
%cinstead:If you want to print the value of the first character in hi, use
%dinstead, with casting:To print the whole string use
%sand pass the pointer: