简体   繁体   English

练习在 printf 函数中使用指针时程序不断崩溃

[英]Program keeps crashing when practicing to use a pointer in a printf function

I'm new to programming.我是编程新手。 I'm attempting to run this extremely simple program as practice to integrate pointers into my code.我正在尝试运行这个极其简单的程序作为将指针集成到我的代码中的练习。 When I run the program, it crashes on startup with a Windows has encountered an unexpected error pop-up.当我运行该程序时,它在启动时崩溃, Windows has encountered an unexpected error弹出窗口。 Absolutely no errors are given for the code itself, but the pop-up persists.代码本身绝对没有错误,但弹出窗口仍然存在。

I'm running the code so far on Code::Blocks, and the program comes up with the stated pop-up from Windows on startup.到目前为止,我在 Code::Blocks 上运行代码,该程序在启动时从 Windows 中弹出指定的弹出窗口。 I have also tested the program on codepad.org and the only error message that comes up has to do with the first line (the include statement).我还在 codepad.org 上测试了该程序,出现的唯一错误消息与第一行(include 语句)有关。 The error states: Segmentation fault .错误状态: Segmentation fault

#include <stdio.h>
int main() {
    // Setting a variable to store the value 15.
    unsigned short int random_number = 15;
    // Defining my pointer.
    unsigned short int *number_pointer;
    // Setting the pointer to hold the memory address of my first variable.
    number_pointer = random_number;
    // Attempting to print the value at the memory address stored in the pointer.
    printf("This code will now print a number: %i", *number_pointer);
    return 0;
}

I expect the output to be: This code will now print a number: 15. , however I didn't even get an output due to the program crashing.我希望输出是: This code will now print a number: 15. ,但是由于程序崩溃,我什至没有得到输出。

Here这里

number_pointer = random_number;

number_pointer is of pointer type, and it should initialized with some valid address , not some value. number_pointer是指针类型,它应该用一些有效的 address初始化,而不是一些值。 In fact above statement causes compiler to warn you like事实上,上面的语句会导致编译器警告你

warning: incompatible integer to pointer conversion assigning to 'unsigned short *' from 'unsigned short';警告:从 'unsigned short' 分配给 'unsigned short *' 的不兼容整数到指针转换; take theaddress with & [-Wint-conversion]用 & [-Wint-conversion] 取地址

but you seems ignored that.但你似乎忽略了这一点。 Never ignore compiler warnings.永远不要忽略编译器警告。 Always compile code with minimal warning flags like -Wall & read those warnings.始终使用最少的警告标志(如-Wall )编译代码并阅读这些警告。 for eg例如

gcc -Wall -Wextra -Wpedantic -Werror test.c  

The number_pointer needs to be point to address of random_number , so that you can de-reference it like *number_pointer . number_pointer需要指向random_number地址,以便您可以像*number_pointer一样取消引用它。

It should be它应该是

number_pointer = &random_number; /* assign the address of random_number */

The comment评论

// Setting the pointer to hold the memory address of my first variable.

seems correct but the commented code is not:似乎正确,但注释代码不是:

number_pointer = random_number;

random_number is a number, number_pointer is a pointer. random_number是一个数字, number_pointer是一个指针。
Number and pointer are different types and the compiler should warn you that they are incompatible types.数字和指针是不同的类型,编译器应该警告您它们是不兼容的类型。

Assigning a value to a variable of an incompatible type leads to data loss (when the variable's type uses less bytes than the value's type).为不兼容类型的变量赋值会导致数据丢失(当变量的类型使用的字节数少于值的类型时)。 But the main danger when data of incompatible types is assigned is the corruption of the data.但是分配不兼容类型的数据时的主要危险是数据损坏。

In your case, the value of number_pointer ( 15 , which is a number) is stored into the variable random_pointer .在您的情况下, number_pointer15 ,这是一个数字)的值存储到变量random_pointer When the value of random_pointer is used, 15 is interpreted as a pointer, ie an address in memory and this is completely wrong.当使用random_pointer的值时, 15被解释为一个指针,即内存中的地址,这是完全错误的。

The expression *number_pointer then tries to read the memory at that address and this leads to an access error that is penalized by the OS (which terminates your program).然后表达式*number_pointer尝试读取该地址处的内存,这会导致访问错误,该错误会受到操作系统的惩罚(它会终止您的程序)。

The source of the problem is the missing & (the "address of" operator) in front of random_number in the assignment above.问题的根源在于上面赋值中random_number前面缺少& (运算符的“地址”)。 It should read:它应该是:

number_pointer = &random_number;

This means the variable number_pointer (of type "pointer to an int") will store the address of variable random_number (of type "int").这意味着变量number_pointer (类型为“指向 int 的指针”)将存储变量random_number (类型为“int”)的地址。 They are compatible and the logic of the program is correct.它们是兼​​容的,程序的逻辑是正确的。 Using the dereference operator ( * ) then successfully reads the integer value stored at the address stored in the number_ponter variable.然后使用取消引用运算符 ( * ) 成功读取存储在number_ponter变量中的地址处的整数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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