1
#include <stdio.h>

  int main(void){
   char c[8];
   *c = "hello";
   printf("%s\n",*c);
   return 0;
   }

我最近在学习指针。上面的代码给了我一个错误 - 赋值从没有强制转换的指针中生成整数[默认启用]。我在 SO 上阅读了一些关于此错误的帖子,但无法修复我的代码。我将 c 声明为任何 8 个字符的数组,c 具有第一个元素的地址。因此,如果我执行 *c = "hello",它将在一个字节中存储一个字符,并根据需要为 "hello" 中的其他字符使用尽可能多的后续字节。请有人帮我确定问题并帮助我解决它。标记

4

2 回答 2

1

我将 c 声明为任何 8 个字符的数组,c 具有第一个元素的地址。- 是的

因此,如果我执行 *c = "hello",它将在一个字节中存储一个字符,并根据需要为 "hello" 中的其他字符使用尽可能多的后续字节。- 否。“hello”的值(指向某个静态字符串“hello”的指针)将分配给 *c(1byte)。"hello" 的值是指向字符串的指针,而不是字符串本身。

您需要使用 strcpy 将一个字符数组复制到另一个字符数组。

const char* hellostring = "hello";
char c[8];

*c = hellostring; //Cannot assign pointer to char
c[0] = hellostring; // Same as above
strcpy(c, hellostring); // OK
于 2014-09-01T07:27:28.563 回答
1
#include <stdio.h>

   int main(void){
   char c[8];//creating an array of char
   /*
    *c stores the address of index 0 i.e. c[0].  
     Now, the next statement (*c = "hello";)
     is trying to assign a string to a char.
     actually if you'll read *c as "value at c"(with index 0), 
     it will be more clearer to you.
     to store "hello" to c, simply declare the char c[8] to char *c[8]; 
     i.e. you have  to make array of pointers 
    */
   *c = "hello";
   printf("%s\n",*c);
   return 0;
 }

hope it'll help..:)

于 2014-09-01T16:03:04.597 回答