#编程语言:C
作为初学者,最近已经学到链表了,但是我遇到了一个小问题
问题在最底下
代码:
主函数
#include "linktest.h"
#include
/**
* 主函数
*/
int main(void)
{
Node *Head = NULL;
int n = 3, i = 0, t;
for ( i = 0 ; i < n ; i++ ) {
scanf("%d",&t);
Head = link_add( Head, t);
}
link_print(Head);
link_free(Head);
}
头文件
#ifndef __LINKTEST_H__
#define __LINKTEST_H__
/**
* 定义结构体Node类型单向链表
*/
typedef struct Node {
struct Node *link; //指向下个Node的指针
int num; //链表编号
int value; //储存的值
} Node;
// Node *link_creat(Node *Head, int n); //声明创建链表函数
Node *link_add(Node *Head, int value); //声明链表添加函数
void link_print(Node *node); //声明输出链表函数
void link_free(Node *Head); //声明释放链表函数
#endif
源文件
#include "linktest.h"
#include
#include
/**
* 链表添加函数
*/
Node *link_add(Node *Head, int value)
{
Node *node = Head, *End = NULL;
static int count = 0;
if ( node ) {
while(node->link) node = node->link;
node->link = (Node *)malloc(sizeof(Node));
node = node->link;
node->value = value;
node->num = count;
node->link = End;
}
else {
node = (Node *)malloc(sizeof(Node));
Head = node;
node->value = value;
node->num = count;
node->link = End;
}
count++;
return Head;
}
/**
* 输出链表函数
* 从头到尾输出链表
*/
void link_print(Node *node)
{
printf("Out putting\n");
while( node ) {
printf("%d %d\n",node->num ,node->value);
node = node->link;
}
printf("Out put down\n");
}
/**
* 释放链表函数
*/
void link_free(Node *Head)
{
printf("Doing free\n");
Node *p, *q;
for( p=Head ; p ; p=q ){
q=p->link;
free(p);
}
printf("Free down\n");
}
上面代码的输出效果:
输入:233 332 666
233 332 666
Out putting
0 233
1 332
2 666
Out put down
Doing free
Free down
问题:
我之前并不想要主函数里每次都愚蠢的给链表Head赋值,所以我把for循环里的
Head = link_add( Head, t);
改成了
link_add( Head, t);
当然了,add的那个函数我也会改为void类型,可是输出是这样的:
233 332 666
Out putting
Out put down
Doing free
Free down
之后我有又改成了这样:
link_add( &(Head), t);
虽然说输出正确了,但是使用gcc编译会给一个warning:
linktestmain.c: In function 'main':
linktestmain.c:15:19: warning: passing argument 1 of 'link_add' from incompatible pointer type [-Wincompatible-pointer-types]
15 | link_add( &(Head), t);
| ^~~~~~~
| |
| Node **
In file included from linktestmain.c:1:
linktest.h:15:22: note: expected 'Node *' but argument is of type 'Node **'
15 | Node *link_add(Node *Head, int value); //澹版 ~~~~~~^~~~
问题就是:
我需要去理这个警告吗?
这个警告重要吗?
我应该怎么改才可以做到既无警告,又不用每次都给Head赋值?