C中的指针乐趣为什么不能编译?

时间:2014-11-22 01:55:33

标签: c pointers

在我开始学习编程之前,我一直以为自己是个聪明人。这是一个无法编译的小例子

#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'来自'char [3]'* dictionary =“ab”;

error.c:11:12:错误:与字符串文字进行比较的结果是       未指定(改为使用strncmp)而(c!=“b”)

error.c:11:12:错误:指针和整数之间的比较       ('int'和'char *')while(c!=“b”)

2 个答案:

答案 0 :(得分:1)

您的代码不正确。甚至没有一点......有点让我认为这是一项家庭作业..但这里有一些提示。

#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 */
}

答案 1 :(得分:1)

除了while中的单引号,你不能做* dictionary =“ab”。

当您取消引用char *(通过执行*字典)时,结果是一个char。您可以初始化char *以指向字符串。如果你在一行中做所有事情就是这样:

char *dictionary = "ab";

否则,你应该这样做:

#include <string.h>

strcpy(dictionary, "ab");