简体   繁体   中英

Pointers in C with Segmentation fault (core dumped) error

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 pointer print_func(hi) . And if you want to print the address of a string, it is better to use %p in printf:

printf("%p \n", hi); // print the address of hi

If you want to print the first character in hi, use %c instead:

printf("%c \n", *hi); // print first character of hi

If you want to print the value of the first character in hi, use %d instead, with casting:

printf("%d \n", (int)*hi); // print the value of the first character of hi

To print the whole string use %s and pass the pointer:

printf("%s \n", hi);

That's because you are passing a character value to the function and giving that as the address to the pointer variable "hi" in print_func. If your program was aimed at printing the string then this would be good -->

#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("%s \n", hi);
}

Even in the second case, I see a problem.

print_func(&hi);

You are passing the address of the pointer while you have to pass just pointer itself. Drop the & in function call.

Well, your function is waiting a string as parameter, and you send a character or a pointer to string !

If you want to print the first character of the string, you should just send your string.

print_func(hi);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM