带有分段错误(核心转储)错误的 C 中的指针 [英] Pointers in C with Segmentation fault (core dumped) error
问题描述
我只是想测试我是否正确安装了新的 ide 并尝试在 IDE 中以及使用 gedit 和 GCC 编译这个基本程序,它可以编译,但在我在命令行中启动可执行文件后崩溃 -我不知道出了什么问题,因为我对 C 中的指针还很陌生,根据大多数人的说法,需要一段时间来理解这个理论.
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.
代码:
#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);
}
我试过了:
#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);
}
它输出 44,没有崩溃.
and it outputs 44 with no crash.
推荐答案
如果您使用 print_func(*hi);
进行间接寻址,则您传递的是一个字符,它是一个字节.因此,当您尝试读取一个更大的整数时,就会发生访问冲突.您应该使用指针print_func(hi)
调用您的函数.而如果要打印字符串的地址,最好在printf中使用%p
:
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
如果要打印 hi 中的第一个字符,请改用 %c
:
If you want to print the first character in use %c
instead:
printf("%c \n", *hi); // print first character of hi
如果要打印 hi 中第一个字符的值,请改用 %d
,并进行强制转换:
If you want to print the value of the first character in use %d
instead, with casting:
printf("%d \n", (int)*hi); // print the value of the first character of hi
要打印整个字符串,请使用 %s
并传递指针:
To print the whole string use %s
and pass the pointer:
printf("%s \n", hi);
这篇关于带有分段错误(核心转储)错误的 C 中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!