c - 无法打印动态分配的指针

标签 c pointers

嗨,因为我正在学习 C 和 C++,所以在使用编码术语时我会犯很多错误,问题是:

为什么我无法打印 *p 的值? malloc 不会返回 NULL 指针;那么为什么它会出现段错误呢?

我读到空指针与未分配的指针不相等。

代码:

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

int main()
    {
    int *p = malloc(sizeof(int));

    p= 100;

    printf("Value of p is: %d \n",p);
    printf("value of *p is: %d \n",*p);
    printf("Value of &p is: %d \n",&p);


    }

终端输出:

rtpl@rtpl-desktop:~/Desktop$ ./practice_output 
Value of p is: 100 
Segmentation fault (core dumped)

第二秒时终端输出 printf语句被注释掉:

rtpl@rtpl-desktop:~/Desktop$ ./practice_output 
Value of p is: 100 
Value of &p is: -1514709824 

此外,我很确定我的问题标题不正确:请告诉我应该将其更改为什么

最佳答案

首先检查 malloc 的返回值和*p=100你想做的事。否则,您将更改指针的值。并且存在内存泄漏。

p的值应打印 %pprintf("%p",p);

还有free使用完后动态分配的内存。

<小时/>
int main()
{
    int *p = malloc(sizeof(int));
    if( p == NULL)
    {
       fprintf(stderr,"%s","Error in allocation");
       exit(1);
    }
    *p= 100;

    printf("Value of p is: %p \n",p);
    printf("value of *p is: %d \n",*p);
    printf("Value of &p is: %p \n",&p);
    free(p);

}

--

此外,当您想将某些内容分配给指针变量时,您必须将其转换为正确的类型。

int *p;
p = (int*)0x12f3ff;

访问某些内存不足的地址或使用错误的格式说明符会导致未定义的行为。

关于c - 无法打印动态分配的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47216434/

相关文章:

C 函数定义和声明

c++ - 在 C++ 中重载字符串的左移运算符

objective-c - 为什么 fget 不工作?

Objective-C:IBaction 中的 while 循环?

c++ - 模式匹配算法

c - C 头文件中的杂散#

C-错误 : request for member ‘---’ in something not a structure or union

arrays - 传递对数组元素的引用以加速

c - 通过 C 中具有位字段的结构指针访问无符号整数的各个位

c++ - C++语法差异:2D和1D数组(指针算术)