我有一维指针数组,我用它来存储链表的头部。我声明并填写这些陈述
struct node { long int val; struct node *next; }; //Our node structure
struct node **pointArray;
pointArray = malloc(size_Of_array * sizeof(struct node *));
for (z =0; z<sizeof(pointArray); z++)
pointArray[z] = NULL;
/*
do something else
...
...
*/
while(numRead <= bytesPerThread) //loop1
{
m = read(fd, buff, sizeof(buff));
numRead += m;
if (m < 0)
handle_error("Read error\n");
else
{
for (i=0; i< m; i++) //loop2
{
if (buff[i] == '#')
while(buff[i] != '\n')
{
i++;
continue;
}
else //else 2
{
if(buff[i] !=' ' && buff[i]!='\n' && buff[i] !='\t')
{ temp[a] = buff[i];
a++;
}
else //else 1
{ Node = atoi(temp);
a = 0;
for (x=0; x< 15; x++)
temp[x] = '\0';
if ((buff[i] == ' ' || buff[i] == '\t') && curruntNode == -1)//just for first time
{
head = (struct node*) malloc(sizeof(struct node));
head->val = Node; //create first node, i.e. head
head->next = NULL;
current = head; //Set current node to head
pthread_mutex_lock(&myLock);
pointArray[Node] = head;
pthread_mutex_unlock(&myLock);
curruntNode = Node;
} else
if (buff[i] == '\n')
{
temp2 = (struct node*) malloc(sizeof(struct node));
temp2->val = Node;
temp2->next = NULL;
current->next = temp2;
current = temp2;
} else
if ((buff[i] == '\t' || buff[i] ==' ') && curruntNode != Node)
{head = (struct node*) malloc(sizeof(struct node));
head->val = Node; //create first node, i.e. head
head->next = NULL;
current = head; //Set current node to head
pthread_mutex_lock(&myLock);
if (pointArray[Node] == NULL)
{
pointArray[Node] = head;}
else
{
current = pointArray[Node];
while (current->next != NULL)
{
current = current->next;
}
current->next = head;
current = head;
}
pthread_mutex_unlock(&myLock);
curruntNode = Node;}
然后我声明指向每个链表中的搜索
for (j = NodesToSeek; j < NodesPerThread; j++)
{printf("hee");
if (pointArray[j] == NULL)
{printf("Null");continue;}
else
{
firstNode = pointArray[j];
printf("1node %ld",firstNode->val);
firstNode = firstNode ->next;
while (firstNode != NULL)
{
move = firstNode;
while (move != NULL)
{
comparedNode = pointArray[firstNode->val];
comparedNode = comparedNode->next;
while (comparedNode != NULL)
{
if (comparedNode->val == move->val)
{
pthread_mutex_lock(&myLock);
tringles++;
pthread_mutex_unlock(&myLock);
}
comparedNode = comparedNode->next;
}//end while
move = move->next;
}//end while
firstNode = firstNode->next;
}//end while
}//end else
}//en
此声明中出现问题
comparedNode = comparedNode->next;
此指针保持为空 谁能告诉我为什么会这样呢?
答案 0 :(得分:0)
pointArray = malloc(size_Of_array * sizeof(struct node *));
for (z =0; z<sizeof(pointArray); z++)
pointArray[z] = NULL;
sizeof(pointArray)返回示例中指针的大小(以字节为单位),而不是数组中的元素数。如果size_Of_array&lt; sizeof(pointArray)然后一些数组未初始化,使得以下代码非常危险。
// It's possible pointArray[Node] is not initialized here
if (pointArray[Node] == NULL)
{
pointArray[Node] = head;
}
else
{
...
您已经知道数组的大小,所以只需将其用于循环。
pointArray = malloc(size_Of_array * sizeof(struct node *));
for (z =0; z<size_Of_array; z++)
pointArray[z] = NULL;