-5

我在中有一个问题是

int **ptr; 
printf("%d\n",**ptr); 

如何在4中使用这些语句打印?

这里我有两个陈述,答案应该是4

我们可以在两个语句之间添加任何语句,但无需声明新变量。

即使使用 ,我也尝试了更多malloc,但我没有解决这个问题。

4

3 回答 3

4

关于什么?

#include <stdio.h>
#include <stdlib.h>
int main() {
    int **ptr;
    ptr = malloc(sizeof(int *));
    *ptr = malloc(sizeof(int));
    **ptr = 4;
    printf("%d\n", **ptr);
}
于 2016-08-26T06:30:32.660 回答
3

好的,根据你的要求,你可以写

int **ptr; 
puts("4");
exit(0);
printf("%d\n",**ptr);

实际答案

不要在没有正确理解需求的情况下尝试编写代码。首先尝试理解输入代码行的目的。

如果您正在寻找指针指针的用法,您可以尝试类似

int **ptr = NULL;
ptr = malloc(sizeof(**ptr));       //allocate memory to ptr first
if (ptr)                          //malloc is success?
{
   *ptr = malloc(sizeof*ptr);        //allocate memory to *ptr
}

if (*ptr) **ptr = 4;                 //finally, put the value in **ptr
printf("%d\n",**ptr);                //go ahead, print it

free(*ptr);             //don't forget this
free(ptr);              //don't forget that, either

但是,如果你不理解为什么部分,就很难得到如何部分。

PS-Code 内嵌注释可帮助您理解这一点,并为您提供进一步阅读的“指针”。

于 2016-08-26T06:28:00.303 回答
1
#include <stdio.h>

int main(void){
    int **ptr; 
    ptr = (int *[]){&(int){ 4 }};
    printf("%d\n",**ptr);
    return 0;
}
于 2016-08-26T06:43:06.837 回答