指针增量和间接引用(左值所需错误) [英] pointer increment and dereference (lvalue required error)

查看:164
本文介绍了指针增量和间接引用(左值所需错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解指针递增和提领走在一起,我这样做是为了尝试一下:

 的#include<&stdio.h中GT;
INT主(INT ARGC,CHAR *的argv [])
{
    字符*字[] = {字词1,字词2};
    的printf(%P \\ N字);
    的printf(%S \\ n,*字++);
    的printf(%P \\ N字);
    返回0;
}

我预计在code做的其中之一:


  1. 先解引用再增加指针(印刷字1)

  2. 先解引用然后增加值(印刷ord1)

  3. 取消引用指针+ 1(印刷字词2)

但是编译器甚至不会编译这一点,并给出了此错误:<?code>左值要求作为增量的操作数我在这里做得不对<​​/ P>

解决方案

您不能增加一个数组,但你可以增加一个指针。如果转换声明一个指针数组,你会得到它的工作:

 的#include&LT;&stdio.h中GT;
INT主(INT ARGC,CHAR *的argv [])
{
    为const char * WW [] = {字词1,字词2};
    为const char **字= WW;
    的printf(%P \\ N字);
    的printf(%S \\ n,*字++);
    的printf(%P \\ N字);
    返回0;
}

I am trying to understand how pointer incrementing and dereferencing go together, and I did this to try it out:

#include <stdio.h>
int main(int argc, char *argv[])
{
    char *words[] = {"word1","word2"};
    printf("%p\n",words);
    printf("%s\n",*words++);
    printf("%p\n",words);
    return 0;
}

I expected this code to do one of these:

  1. First dereference then increase the pointer (printing word1)
  2. First dereference then increase the value (printing ord1)
  3. Dereference pointer + 1 (printing word2)

But compiler won't even compile this, and gives this error: lvalue required as increment operand am I doing something wrong here?

解决方案

You cannot increment an array, but you can increment a pointer. If you convert the array you declare to a pointer, you will get it to work:

#include <stdio.h>
int main(int argc, char *argv[])
{
    const char *ww[] = {"word1","word2"};
    const char **words = ww;
    printf("%p\n",words);
    printf("%s\n",*words++);
    printf("%p\n",words);
    return 0;
}

这篇关于指针增量和间接引用(左值所需错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆