简体   繁体   English

C中的指针增量

[英]Pointer Increment in C

I am getting an odd error in a small C program in which I'm trying to learn how to use pointers. 我在试图学习如何使用指针的小型C程序中遇到一个奇怪的错误。

I assumed everything was working because it compiled but when I try to run the code, it says C program has stopped responding. 我认为一切正常,因为它已编译,但是当我尝试运行代码时,它说C程序已停止响应。 I must be doing something incorrect... Any help? 我一定做错了什么...有什么帮助吗?

#include <stdio.h>


int main()
{

int k = 22;
int z = 11;
int *ptr = k;

 printf("%d \n",*ptr);
 ptr++;
 printf("%d \n",*ptr);




    getchar();
    return 0;
}

You need to assign address of k not it's value.. 您需要分配地址k而不是它的值。

int *ptr = &k;

Also after ptr++; 同样在ptr++; *ptr would print garbage value(though behavior is undefined) *ptr将打印垃圾值(尽管行为未定义)

Your problem is here: 您的问题在这里:

int *ptr = k;

you are assigning the value of k to ptr not the address of, so you are missing the address operator( & ): 您将k的值分配给ptr而不是其地址,因此缺少地址运算符( & ):

int *ptr = &k;
           ^

gcc by default gives the following warning: 默认情况下, gcc发出以下警告:

warning: initialization makes pointer from integer without a cast [enabled by default] 警告:初始化会使指针从整数开始而没有强制转换[默认启用]

So if you are not seeing a waring then you should enable warnings. 因此,如果您没有看到警告,则应启用警告。

Performing indirection on ptr after you increment here: 在此处递增后,对ptr执行间接操作:

ptr++;
printf("%d \n",*ptr);
               ^
               indirection

it is undefined behavior in this case since it will be pointing to one past the last element, since pointers to non-arrays are treated as 1 element arrays for this case as per C99 section 6.5.6 Additive operators paragraph 7 . 在这种情况下,这是未定义的行为,因为它将指向最后一个元素之后的一个,因为根据C99第6.5.6节“ 加法运算符”7节,指向非数组的指针在这种情况下被视为1个元素数组。

It is very simple to understand pointer, the pointer is a value to store an memory address, and you must always ensure the memory address is avaiable! 指针非常简单,指针是存储内存地址的值,您必须始终确保内存地址可用!

so here is the 1st error; 所以这是第一个错误;

int *ptr = k;

so 1st you shall assign an valid memory address to the ptr before you use it, correct one shall be 因此,首先您应在使用之前为ptr分配一个有效的内存地址,正确的是

int *ptr;
ptr = &K

star (*) is use to get the value which is stored in the memory address you assigned. 星号(*)用于获取存储在您分配的内存地址中的值。 so to increase the value , you shall 为了增加价值,您应

(*ptr)++ 

instead of 代替

ptr++

this will increase the address instead of value itself, and you r really unknown what is stored there. 这将增加地址而不是值本身,并且您真的不知道在那里存储了什么。

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

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