【问题标题】:Pointer to Scanf with malloc, unpredictable results指向带有 malloc 的 Scanf 的指针,不可预测的结果
【发布时间】:2013-04-27 14:15:13
【问题描述】:

我试图让我的程序使用指针和 malloc 将 Scanf 的结果存储到内存中,我希望 Scanf 只能接受整数,这是我的代码。当我打印结果时,它会返回一个随机数??

int main(void)
{

unsigned int *Source = malloc(10);
printf("Enter a Source Number: ");
scanf("%i",Source);
printf("%i\n",Source);
unsigned int *Destination = malloc(4);
printf("Enter a Destination Number: ");
scanf("%i",Destination);
printf("%i\n",Destination);
unsigned int *Type = malloc(4);
printf("Enter a Type Number: ");
scanf("%i",Type);
printf("%i\n",Type);
int *Port = malloc(4);
printf("Enter a Port Number: ");
scanf("%i",Port);
printf("%i\n",Port);
char *Data;
struct Packet *next;

return 0;
}

谁能解释一下?

【问题讨论】:

    标签: c pointers malloc scanf


    【解决方案1】:
    printf("%i\n",Source);
    

    是未定义的行为,%i 转换需要 int,但您传递的是 int*。但它可能会尝试将指针值(地址)打印为int。你打算使用

    printf("%i\n", *Source);
    

    那里。其他printfs 也是如此。

    传递给malloc的硬编码值并不是一个特别健壮的想法,更好的是malloc根据指针的大小,

    unsigned int *Source = malloc(sizeof *Source);
    

    【讨论】:

    • 哦,呵呵!谢谢,@undefined 行为。
    【解决方案2】:
    unsigned int *Source = malloc(10);
    

    源是一个指针。

    printf("%i\n",Source);
    

    这段代码是打印值的地址,打印值是这样的:

    printf("%i\n",*Source);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-03
      • 2012-08-17
      • 1970-01-01
      • 2018-04-03
      • 2018-12-03
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      相关资源
      最近更新 更多