检查结构数组是否为空

时间:2013-10-08 14:11:38

标签: c

我该怎么做?例如

        typedef struct node
     {   int data;
         struct node* next;
     }node;

是我的节点,而我的主要是

       int main(){
          node* array[10];
          if (node[0].data == 0){
           ...

                                }

我不确定我需要在这做什么。我希望能够检查数组中的这些条目是否已被修改。我该怎么做?我试过了 - >运算符而不是。这让我有些困惑因为我正在处理一个对象不是我吗?我不确定这一点。

根据建议,这就是我现在所拥有的。

 int main() {
 struct node* arr[10] = { 0 } ;
   addTo(data, arr);
            }


   addTo(int data, node* arr){
        if (arr[0] == NULL)
                             }

最后一行是分段错误。

3 个答案:

答案 0 :(得分:3)

C中的数组不能为“空”。他们永远不会空虚。如果您声明了一个包含10个元素的数组,那么您将始终拥有10个元素的数组。除非你自己想出一些方法来手动“标记”你修改的元素,否则没有办法说明某个元素是否已被修改。例如,您可以选择一些保留元素值,这将指定一个“空”元素。

在您的情况下,您声明一个包含10个指针的数组

node* array[10];

如果您提供初始化程序

node* array[10] = { 0 };

您的数组元素的初始值为null。您可以将该值用作“空”元素的标记。

答案 1 :(得分:2)

       node array[10]; //array of struct node type 
       //node *array[10]; //this becomes declaration of array of pointers

       //assuming you have initialized all with 0.

       for(i=0;i<10;i++)   
       if (array[i].data == 0)   
       //data modified.
       //if you declare array of pointers check if(array[i]->data==0)

答案 2 :(得分:1)

您发布的代码不会导致崩溃,因为它甚至无法编译。我修复了所有明显的错误以摆脱编译器错误,现在它在这里完美无缺地运行而不会崩溃:

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int data;
    struct node* next;
} node;

/* changed node* to node*[] and added return type */
void addTo(int data, node* arr[])
{
    if (arr[0] == NULL)
    {
        puts("yes");
    }
    else
    {
        puts("no");
    }
}

int main()
{
    struct node* arr[10] = { 0 } ;
    /* changed data to 42, because there is no variable data in scope here */
    addTo(42, arr);
}

如果您有任何其他问题,请随时提出。

相关问题