无法打印动态分配的指针

时间:2017-11-10 05:50:58

标签: 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 

另外我很确定我对这个问题的标题不正确:请告诉我应该将它更改为

2 个答案:

答案 0 :(得分:2)

首先检查您要执行的malloc*p=100的返回值。否则,您正在更改指针的值。并且有内存泄漏。

p的值应使用%p打印。 printf("%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;

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

答案 1 :(得分:-1)

{d} p = 100

中的问题没有问题
#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);


    }
相关问题