周梦康 发表于 2014-05-10 3128 次浏览 标签 : C

用代码说话:

#include <stdio.h>

typedef struct {
    int data[20];
    int lenght;
} sequenceList;

int getElement(sequenceList list,int index)
{
    int lenght = list.lenght;
    if (lenght == 0 ||
        index < 0 ||
        index >= lenght
        ) {
        return 0;
    }
    return list.data[index];
}

int getElement2(sequenceList *list,int index)
{
    int lenght = list->lenght;
    if (lenght == 0 ||
        index < 0 ||
        index >= lenght
        ) {
        return 0;
    }
    return list->data[index];
}

int main(){
    sequenceList list = {
        {3,1,10,7,12,78},
        6
    };
    int index = 5;
    int element = getElement(list,index);
    printf("list[%d]: %d\n",index,element);
    
    int element2 = getElement2(&list,index);
    printf("list[%d]: %d\n",index,element2);
}

也就是说用指针的时候就用->,用结构体本身的时候就用.

评论列表