关于malloc问题
n个人围一圈报数,报到3的就退出,求最后一个人是原来的几号#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,j,k;
int*a;
printf("input n:");
scanf("%d",&n);
a=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
*(a+i)=i+1;
i=0;
j=0;
k=0;
while(j<n-1)
{
if(*(a+i)!=0)k++;
if(k==3)
{
k=0;
*(a+i)=0;
j++;
}
i++;
if(i==n)i=0;
}
while(*a==0)a++;
printf("the last one is:%d\n",*a);
}
这是没问题的,可是
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,j,k;
printf("input n:");
scanf("%d",&n);
int*a=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
*(a+i)=i+1;
i=0;
j=0;
k=0;
while(j<n-1)
{
if(*(a+i)!=0)k++;
if(k==3)
{
k=0;
*(a+i)=0;
j++;
}
i++;
if(i==n)i=0;
}
while(*a==0)a++;
printf("the last one is:%d\n",*a);
}
这样就不行了,a指针那样分配内存空间有什么问题吗?下面是问题:
10.5.c(8) : error C2143: syntax error : missing ';' before 'type'
10.5.c(10) : error C2065: 'a' : undeclared identifier
10.5.c(10) : error C2100: illegal indirection
10.5\10.5.c(10) : error C2106: '=' : left operand must be l-value
10.5.c(16) : error C2100: illegal indirection
10.5.c(20) : error C2100: illegal indirection
10.5.c(20) : error C2106: '=' : left operand must be l-value
10.5.c(26) : error C2100: illegal indirection
10.5.c(27) : error C2100: illegal indirection