C 使用指针时出错
我是C新手,但我以前做过一些java编程。我的程序尝试按时间顺序(年、月、日)对日期列表进行排序。但是我遇到了这个错误 警告:赋值从整数生成指针,但未启用强制转换[已启用] 默认情况下]C 使用指针时出错,c,pointers,C,Pointers,我是C新手,但我以前做过一些java编程。我的程序尝试按时间顺序(年、月、日)对日期列表进行排序。但是我遇到了这个错误 警告:赋值从整数生成指针,但未启用强制转换[已启用] 默认情况下] #包括 #包括 #包括 类型定义结构{ 字符*月; 国际日; 国际年; }日期; 整数排序(常量无效*a,常量无效*b) { 日期*日期1=(日期*)a; 日期*日期2=(日期*)b; 如果(日期2->年份!=日期1->年份){ int year2=日期2->year; int year1=日期2->year;
#包括
#包括
#包括
类型定义结构{
字符*月;
国际日;
国际年;
}日期;
整数排序(常量无效*a,常量无效*b)
{
日期*日期1=(日期*)a;
日期*日期2=(日期*)b;
如果(日期2->年份!=日期1->年份){
int year2=日期2->year;
int year1=日期2->year;
如果(第1年<14年){
年份1=年份1+100;
}
如果(第2年<14年){
第2年=第2年+100年;
}
int yearcompare=year2-year1;
回归年比较;
}
返回0;
}
输出(日期*ar,整数i,整数n)
{
对于(i=0;i最大尺寸){
printf(“您输入的数字高于1000\n”);
}
否则{
打破
}
}
//日期*ar=malloc(国际规模)*n;
//分配内存
ar=分配函数(n);
printf(“以以下格式输入日期(月-日-年):文本、数字(介于1和31之间)、数字(介于00和12之间):\n”);
对于(i=0;i
您的allocateStruct
函数是否返回date*
?C中的newb,但是allocateStruct
可能不会返回date*
。更新。抱歉@JHH,发布得太晚了一秒钟不,我最初使用的是date*ar=malloc(sizeof(int)*n)但是这给了我更多的问题。date*ar=malloc(sizeof(int)*n)代码>应为date*ar=malloc(sizeof(date)*n)编码>并分配给月份的成员。同时介于1和10000之间-->介于1和1000之间output(date*ar,int i,int n)
-->无效输出(date*ar,int i,int n)
(您不需要将i
作为参数传递。)allocateStruct
函数是否返回date*
?C中的newb,但allocateStruct
可能不返回date*
。更新。抱歉@JHH,发布得太晚了一秒钟不,我最初使用的是date*ar=malloc(sizeof(int)*n)但是这给了我更多的问题。date*ar=malloc(sizeof(int)*n)代码>应为date*ar=malloc(sizeof(date)*n)编码>并分配给月份的成员。同时介于1和10000之间-->介于1和1000之间<代码>输出(日期*ar,int i,int n)
-->无效输出(日期*ar,int i,int n)
(您不需要将i
作为参数传递。)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char* month;
int day;
int year;
} date;
int sort(const void* a, const void* b)
{
date* date1 = (date*)a;
date* date2 = (date*)b;
if (date2->year != date1->year) {
int year2 = date2->year;
int year1 = date2->year;
if (year1 < 14) {
year1 = year1 + 100;
}
if (year2 < 14) {
year2 = year2 + 100;
}
int yearcompare = year2 - year1;
return -yearcompare;
}
return 0;
}
output(date* ar, int i, int n)
{
for (i = 0; i < n; i++) {
//printf("Enter the date (month day year) i n the following format: text number number");
// printf("%s ", ar[i].month);
//printf("%d ", ar[i].day);
printf("%d\n", ar[i].year);
}
}
int main()
{
int n;
int i;
int MIN_SIZE = 0;
int MAX_SIZE = 1000;
date* ar;
while (1) {
printf("Enter number of dates you want to enter (between 1 and 10000):\n");
scanf("%d", &n);
if (n < MIN_SIZE) {
printf("You have entered a number lower than 0\n");
}
if (n > MAX_SIZE) {
printf("You have entered a number higher than 1000\n");
}
else {
break;
}
}
//date* ar = malloc(sizeof(int) * n);
//ALLOCATE MEMORY
ar = allocateStruct(n);
printf("Enter the date (month day year) in the following format: text, number(between 1 and 31), number(between 00 and 12): \n");
for (i = 0; i < n; i++) {
scanf("%s", ar[i].month);
scanf("%d", &ar[i].day);
scanf("%d", &ar[i].year);
}
qsort(ar, n, sizeof(date), sort);
output(ar, i, n);
return 0;
}