创建使用C列表和结构数组 [英] Creating a list and struct arrays using C

查看:81
本文介绍了创建使用C列表和结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前开始了用C,所以我想我会尝试创建自己的定制名单。这里的code:

I'm currently starting out with C so I thought I'd try creating my own custom list. Here's the code:

#include <stdio.h>

struct list {
    char data[10];
    struct list *n;
};

void clist(struct list *a) {
    int j=(sizeof(a)/sizeof(a[0]));
    j--;    
    for(int i=0; i<j-1; i++) {
        struct list *next=&a[i+1];
        a[i].n=next; 
    }
}

int main() {

    struct list first = {.data="one", .n=NULL};
    struct list second = {.data="two", .n=NULL};
    struct list third = {.data="three", .n=NULL};

    struct list arr[] = {first, second, third}; 
    struct list *p=&arr[0];

    clist(p);

    struct list looper = first;

    while(looper.n!=NULL) {
        printf("%s ", looper.data);
        looper = *looper.n;
    }

    return 0;
}

所以基本上我有一个保存字符数组和指针的结构体。我初始化它们,然后我试图通过他们给它的CLIST方法连接在一起。
然而问题就出:看来CLIST没有得到任何东西作为变量j停留在0。如果我给数组的CLIST方法之前做整体尺寸计算,我得到了正确的3,结果是有用的。这是为什么?

So basically I have a struct that saves a char array and a pointer. I initialize them and then I try to link them together by giving it to the clist method. There lies the problem: it seems clist isn't getting anything useful as the variable j stays at 0. If I do the whole size calculation before giving the array to the clist method, I'm getting the correct 3 as a result. Why is that?

推荐答案

在C,阵列参数都被视为指针。所以前pression 的sizeof(A)/ sizeof的(A [0])变成的sizeof(INT *)/的sizeof(INT)

In C, array parameters are treated as pointers . So the expression sizeof(a)/sizeof(a[0]) becomes sizeof(int *)/sizeof(int).

所以你基本上是越来越为(您的地址有多大)/(整数大小)

So what you are essentially getting is (how big your address is) / (size of integer)

解决这个问题的解决办法是在发送数组元素的数量 A 作为另一个参数的功能。

The solution to this would be to send the number of elements in array a as another parameter to the function.

这篇关于创建使用C列表和结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆