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

被折叠的 条评论
为什么被折叠?



