簡體   English   中英

C語言中的Pointer Fun。為什么不編譯?

[英]Pointer Fun in C. Why won't this compile?

在開始學習編程之前,我一直以為自己是個聰明人。 這是一個無法編譯的小例子

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char* dictionary;
  dictionary = malloc(sizeof(char) * 3);
  *dictionary = "ab";
  char c = dictionary[0];
  int i = 0;
  while (c != "b")
  {
    printf("%c\n", c);
    i++;
    c = dictionary[i];
  }
}

error.c:8:15:錯誤:整數轉換的不兼容指針,從'char [3]'分配給'char'* dictionary =“ ab”;

error.c:11:12:錯誤:未指定與字符串文字的比較結果(改為使用strncmp),而(c!=“ b”)

error.c:11:12:錯誤:指針與整數('int'和'char *')之間的比較,而(c!=“ b”)

您輸入的代碼不正確。 一點也不..有點讓我覺得這是一項家庭作業..但是這里有一些提示。

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char* dictionary;
  dictionary = malloc(sizeof(char) * 3); /* ok, I expect to see a free later */
  *dictionary = "ab"; /* assigning a string literal to a dereferenced char *..
                      /* maybe we should use strncpy..  */
  char c = dictionary[0];
  int i = 0;
  while (c != "b") /* hmm.. double quotes are string literals.. maybe you mean 'b' */
  {
    printf("%c\n", c);
    i++;
    c = dictionary[i];
  }
  /* hmm.. still no free, guess we don't need those 3 bytes.
     int return type.. probably should return 0 */
}

加上一段時間中的單引號,您無法執行* dictionary =“ ab”。

當您取消引用char *(通過執行* dictionary)時,結果是單個char。 您可以將char *初始化為指向字符串。 如果您將所有內容全部放在一行中,那將是:

char *dictionary = "ab";

否則,您應該執行以下操作:

#include <string.h>

strcpy(dictionary, "ab");

暫無
暫無

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

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