如何使用for循环和引用运算符在数组中循环?
private func setupLayout() {
view.addSubview(imageView)
view.addSubview(titleLabel)
// *** imageView ***
if #available(iOS 11.0, *) {
imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 116).isActive = true
} else {
imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 116).isActive = true
}
imageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 224).isActive = true
// *** titleLabel ***
titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 25).isActive = true
titleLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -28).isActive = true
titleLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 28).isActive = true
}
我应该在哪里插入i?
这些是结构:
for (i = 0; i < university->size; i++)
{
if (university->arr->MarkA <= 100)
{
sum += university->arr->MarkA;
count++;
}
我使用了一个函数来创建大学数组
typedef struct Student
{
char *name;
long ID;
int MarkA, MarkB, HW;
}stud;
typedef struct University
{
stud *arr;
int size;
}Uni;
在主函数中,我调用了上述函数以在此结构上工作
void build_Uni(FILE* in, Uni* university)
{
int i = 0;
stud temp;
char Name[100];
while (!feof(in))
{
fscanf(in, "%s%li%d%d%d", Name, &temp.ID, &temp.MarkA, &temp.MarkB, &temp.HW);
i++;
}
university->size = i;
rewind(in);
university->arr = (stud*)malloc(university->size * sizeof(stud));
if (university->arr == NULL) Get_Lost("Memory allocation failed!");
else for (i = 0; i < university->size; i++)
fill_Uni(in, university->arr + i);
}
void fill_Uni(FILE* in, stud* student)
{
char Name[100];
fscanf(in, "%s%li%d%d%d", Name, &student->ID, &student->MarkA, &student->MarkB, &student->HW);
student->name = (char*)malloc((strlen(Name) + 1) * sizeof(char));
if (student->name == NULL) Get_Lost("Error allocatig memory");
strcpy(student->name, Name);
}
答案 0 :(得分:1)
如何使用for循环和引用循环遍历数组 运算符?
我认为您的意思是解引用运算符->
,但引用和解引用与遍历数组无关。这就是您的for循环的目的。
我应该在哪里插入i?
此:
for (i = 0; i < university->size; i++)
{
if (university->arr->MarkA <= 100)
{
sum += university->arr->MarkA;
count++;
}
}
应该是这样
for (i = 0; i < university->size; i++)
{
if (university->arr[i].MarkA <= 100)
{
sum += university->arr[i].MarkA;
count++;
}
}
答案 1 :(得分:1)
关于原始问题,您应该按以下方式访问它:
University university;
...
for (i = 0; i < university.size; i++) {
if (university.arr[i].MarkA <= 100)
{
sum += university.arr[i].MarkA;
count++;
}
...
}
但是,如果university
的类型为University*
,则代码会稍有变化,因为您必须使用运算符->
来访问university
成员:
for (i = 0; i < university->size; i++) {
if (university->arr[i].MarkA <= 100)
{
sum += university->arr[i].MarkA;
count++;
}
...
}