#include<stdio.h>
int main()
{
setbuf(stdout,NULL);
int a[],i,lim,sum=0;
printf("Enter the limit of the array: ");
scanf("%d",&lim);
printf("Enter the values: ");
for(i=0;i<lim;i++)
{
scanf("%d",&a[i]);
}
int *p;
for(p=&a[0];p<lim;p++)
{
sum=sum+*p;
}
printf("Sum= %d",sum);
return 0;
}
在运行代码时,出现以下错误
.. \ src \ Test6.c:在“ main”函数中:
.. \ src \ Test6.c:5:6:错误:'a'中缺少数组大小
.. \ src \ Test6.c:14:15:警告:指针与整数之间的比较
请帮助我理解为什么在没有指针的情况下没有问题时为什么必须声明数组大小。
或者,请帮助我了解我应该进行哪些更改以纠正错误:)
答案 0 :(得分:0)
在声明数组时也声明大小。
例如
int a[100000];
您最多可以在数组中放置100000个元素。
答案 1 :(得分:0)
您的循环
import React, { Component } from "react"; // import material UI card components import Card from '@material-ui/core/Card'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; // useful component for displaying text - multiple variants (body, h1, h2 etc.) import Typography from '@material-ui/core/Typography'; export class Dashboard extends Component { displanyName = Dashboard.name; constructor(props) { super(props); this.state = { people: [] }; } componentDidMount() { fetch("api/people") .then(response => response.json()) .then(data => this.setState({ people: data })); } render() { //const { people } = this.state; // equivalent to next line const people = this.state.people; if (people.length > 0) //creates an array to iterate let arr = people.map((person, index) => ( <Card key={index}> <CardContent> <Typography variant="h5"> Person: {person.name} </Typography> <Typography variant="body2"> Job: {person.job} </Typography> </CardContent> </Card> )); return ( <div> {arr} </div> ); } }
应写为
for(p=&a[0];p<lim;p++)
{
sum=sum+*p;
}
或更通常使用索引,
for (p = &a[0]; p < &a[lim]; p++)
{
sum += *p;
}