【问题标题】:Pointer initialization. How does it work?指针初始化。它是如何工作的?
【发布时间】:2014-05-30 08:19:47
【问题描述】:

我用 C 完成了我的编程课程,并认为我会写下一些代码。繁荣!我遇到了很多问题。我猜C语言太复杂了,即使是一本书也无法完全解释它是如何工作的。

这是我的问题(我正在尝试使用指针显示某些内容)

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

void main()
{
   char *a;
   system("cls");
   *a = {"hello"};
   printf("%s",a);
   getch();
}

【问题讨论】:

  • 其实很多书都很好的解释了指针。你读过哪些书不够用?
  • @paddy 我猜 Niit 的书没有解释它
  • K&R 是一本非常简短的书,它完整地解释了 C 语言。
  • @FilipeGonçalves K&R 是一本好书,但由于它自 1988 年以来一直没有修订,因此它没有涵盖当前 C 语言的重要部分。
  • @NigelHarper 完全同意,但是对于初学者来说这是一个很好的介绍

标签: c dev-c++


【解决方案1】:
*a = {"hello"};

这取消了指针的引用并为该内存位置分配了一些东西。它崩溃的原因是因为指针未初始化,它没有指向任何东西(实际上它确实指向了某个东西,但那个东西是一个未定义的内存位置)。

如果您执行了以下操作,您的程序就会运行:

a = "hello";

a 的类型是char*"hello" 的类型也是char*

【讨论】:

  • 感谢您的回答,但您能告诉我整个工作代码吗?我会很高兴
【解决方案2】:

您不会以这种方式为指向 char 的指针赋值:

*a = {"hello"};

你必须使用:

a="hello";

我不太了解您要做什么。如果您只想在屏幕上打印“hello”,为什么要使用指向 char 的指针? getch() 有什么用?你这样使用那个函数:http://linux.die.net/man/3/getch你打算读一个字符吗?

我只会这样做:

#include <stdio.h>

main()
{
    printf("hello");
}

你到底想做什么?

这是一个很好的参考指南:http://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html

【讨论】:

    【解决方案3】:
    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>
    
    void main()
    {
        char *a;// a  is pointer which address is store in stack and when u initialize with any string then string is store in code section which cant be change
        clrscr();
        a = "hello";// this is the way to store the string but if when u assign while declaring as char *a= hello this will accept Remember hello is store in code where as address of pointer a is store in stack section   
    
        printf("%s", a);
        getch();
    }
    

    ~

    【讨论】:

      【解决方案4】:

      只是为您提供另一种见解.. 刚才我在 Dev-C++ 5.6.3 中尝试过这个,它可以工作..

      如果你在声明时直接赋值,它会起作用:

      #include <stdio.h>
      #include <stdlib.h>
      #include <conio.h>
      
      int main()
      {
          system("cls");
          char *a = {"hello"};
          printf("%s",a);
          getch();
      
          return 0;
      }
      

      还有一件事,clrscr 不是标准的 c 函数(它在我的测试中不起作用),那么像我一样在stdlib 中使用cls 怎么样.. 希望它有用..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-08
        • 1970-01-01
        • 2017-01-30
        • 1970-01-01
        • 1970-01-01
        • 2011-04-10
        • 2016-11-09
        相关资源
        最近更新 更多