簡體   English   中英

這段代碼有什么問題? 它給出錯誤 - 需要作為增量操作數的左值

[英]What's wrong with this code? It gives error - lvalue required as increment operand

我不明白為什么這段代碼是錯誤的,它說需要左值作為增量操作數。 但是行星不是指向字符串的指針數組嗎? 所以行星++不應該把我帶到下一個字符串。 例如,planets 是指向字符串“mercury”的指針。 當我做行星++時,它不應該帶我去“金星”嗎

#include <stdio.h>

int main()
{

    char* planets[] = {"Mercury", "Venus", "Earth","Mars","Jupiter",
                        " Saturn", "Uranus", "Neptune", "Pluto"};


    int count = 0;
    for(planets; planets <= planets + 8;planets++){
        if(**planets == 'M'){
            count++;
        }// if 

    }// for

    printf("\n%d",count);

}

你對planets的描述是准確的; 它被定義為一個指針數組。 強調其中的數組部分,因為這意味着使用它的 id 不符合后增量等左值操作的資格。

如果您想使用指針表示法遍歷該指針數組,則可以使用鍵入數組類型的正確指針來完成。 如果數組是const char*的數組,則指向const char *的指針(即const char ** )是合適的。

像這樣:

#include <stdio.h>

int main()
{
    const char *planets[] = {
        "Mercury", "Venus", "Earth", "Mars", "Jupiter",
        "Saturn", "Uranus", "Neptune", "Pluto"
    };


    int count = 0;
    for(const char **p = planets; p != planets + 9; ++p)
    {
        if(**p == 'M'){
            count++;
        }// if
    }// for

    printf("%d\n",count);
}

Output

2

變量planets是一個數組,所以你不能增加它。

而是使用 integer 作為循環中的索引:

#include <stdio.h>

int main()
{

    char* planets[] = {"Mercury", "Venus", "Earth","Mars","Jupiter",
                        " Saturn", "Uranus", "Neptune", "Pluto"};


    int count = 0;
    for(int i = 0; i < 9; i++){
        if(planets[i][0] == 'M'){
            count++;
        }// if 

    }// for

    printf("\n%d",count);

}

如其他答案所述, char *planets[]定義了一個字符串數組。 編譯器會將planets視為固定在陣列上的 label,並且(通常)不允許移動 label。 因此,最好的選擇是(如此處的其他答案所示)對數組進行索引,或者使用輔助指針來遍歷數組。

我喜歡在 arrays 中添加一個結尾NULL ,它在使用輔助指針行走時提供了一個停止點。 例如:

  #include <stdio.h>

  int main()
    {
    char *planets[] = {"Mercury", "Venus", "Earth","Mars","Jupiter",
                        " Saturn", "Uranus", "Neptune", "Pluto", NULL};
    char **planet;

    int count = 0;
    for(planet = planets; *planet; planet++)
      {
      if(**planet == 'M')
            count++;
      }

    printf("%d\n",count);
    }

關於:

for(planets; planets <= planets + 8;planets++){  

這會導致編譯器發出以下消息:

:11:48: error: lvalue required as increment operand

但是變量planets位於地址,固定在memory,所以不能更改。 建議

for( char *string = 行星; 字符串 <= 行星+8; 字符串++ )

然后在for()循環體中使用變量string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM