(1)malloc:assignment from incompatible pointer type -(2)declaration of function ‘gets’; ‘fgets

本文探讨了C语言中使用malloc分配内存时遇到的问题,包括内存匿名性及返回地址赋值给字面量可能导致的数据类型不匹配警告。通过代码示例验证了这些问题并强调了类型转换的必要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

arning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
     str1 = (int*)malloc(sizeof(int) * 30);
     :16:10: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
     str2 = (int*)malloc(sizeof(int) * 30);
          ^
10.2.10比较字符串的大小.c:18:5: warning: implicit declaration of function ‘gets’; did you mean ‘fget’? [-Wimplicit-function-declaration]
     gets(str1);
     ^~~~
     fgets

在这里插入图片描述

Malloc分配内存没有标识符:内存是匿名的,返回内存首字节的地址(该地址赋予一个指针)

在这里插入图片描述

直接将地址的首地址的赋予给字面量 ptd,不是指向内存分配的真个块?

在这里插入图片描述

验证一下:会有警告数据类型的强制转换。。。在这里插入图片描述在这里插入图片描述

代码:

/**
 * 字符串由键盘输入
 * 怎么用数组接受键盘的输入的字符
 *
*/
#include <stdio.h>
#include <stdlib.h>
#define N 30
extern int str_cmp(char *a, char *b);
void main()
{
    int k;
    char *str1, *str2;
    //如果想使用malloc呢
    str1 = (char *)malloc(sizeof(char) * 30);
    str2 = (char *)malloc(sizeof(char) * 30);
    printf("input string\n");
    fgets(str1, 30, stdin);
    printf("Please input the second string:\n");
    fgets(str2, 30, stdin);
    if ((k = str_cmp(str1, str2)) > 0)
        printf("first is bigger");
    else if (k == 0)
    {
        printf("two string are equal");
    }
    else
    {
        printf("The second is bigger");
    }
}
int str_cmp(char *a, char *b)
{
    int i;
    for (i = 0; a[i] == b[i]; i++)
    {
        if (a[i] == '\0')
        {
            return 0;
        }
    }
    return (a[i] - b[i]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值