链接列表/指针的问题
问题描述:
我目前在C中存在链接列表和指针问题。我遇到的问题是将数据添加到链接列表中。目前,我有:链接列表/指针的问题
struct str_pair{
char ip [50] ;
char uri [50] ;
struct str_pair *next ;
};
struct str_pair *it ;
struct str_pair *header = NULL; // Start of linked list
struct str_pair *ptr; // Moves along the list
struct str_pair *ptr2; // Another pointer
struct str_pair *ptr3;
void addData(char *addURI, char *addIP){
struct str_pair *tmp, *tmp2;
tmp = (str_pair*)malloc(sizeof(str_pair)); // Create new space in str_pair
strncpy(tmp->uri, addURI, 49);
strncpy(tmp->ip, addIP, 49);
tmp->next = NULL;
if (header == NULL) { header = tmp; }
else
{
tmp2 = header;
while (tmp2->next != NULL) { tmp2 = tmp2->next; }
tmp2->next = tmp;
}
}
我想要做的是通过一个URL和IP地址,通过它应该加上这些值到链表中的参数。
这里是代码调用这个函数:
int main(int argc, char *argv[])
{
int incrItems=0;
int j;
header = NULL;
for(j = 1; j < argc; j++)
{
char ch=argv[j][0];
switch(ch)
{
case 'A' :
{
char *newURI = argv[j+1];
char *newIP = argv[j+2];
incrItems++;
addData(newURI,newIP);
j=j+2;
break;
}
*Snipped the rest as its unnecessary*
我遇到的问题是,传递的参数没有被添加到链表。编译时不显示错误。
答
for(j = 1; j < argc; j++)
{
switch(argv[j][0]) { /* no need to copy */
case 'A' :
incrItems++;
/* assert (j+2 < argc); */
addData(argv[j+1], argv[j+2]); /* no need to copy */
j=j+2;
break;
case 'B' :
default:
...
break;
}
}
编辑:注:上面没有溶液,仅仅一个提示。 另一个提示:
#include <stdlib.h>
#include <string.h>
void addData(char *addURI, char *addIP){
struct str_pair *tmp, **hnd;
tmp = malloc(sizeof *tmp);
/* assert (tmp != NULL); */
strncpy(tmp->uri, addURI, 49); tmp->uri[49] = 0;
strncpy(tmp->ip, addIP, 49); tmp->ip[49] = 0;
tmp->next = NULL;
for (hnd = &header; *hnd; hnd = &(*hnd)->next) {;}
*hnd = tmp;
}
+0
现在,老师会认为乔治是一个聪明的孩子; - } – wildplasser
+0
哈哈哈不太亮:),我迟到了,所以我花时间处理你的“提示”。感谢您的帮助:D。 – George
答
如果你在一个for,你为什么增加j变量?另外,尝试将一些printf添加到add函数中,以了解参数是否正确。
答
尽管wildplasser提供了很好的提示,但代码工作得很好。
int main(int argc, char *argv[])
{
int incrItems=0;
int j;
header = NULL;
for(j = 1; j < argc; j++)
{
char ch=argv[j][0];
switch(ch)
{
case 'A' :
{
char *newURI = argv[j+1];
char *newIP = argv[j+2];
incrItems++;
printf(" Adding %s %s\n", newURI, newIP);
addData(newURI,newIP);
j=j+2;
break;
}
}
}
printf(" J at end is %d\n",j);
it = header;
if(it != NULL)
do {
printf(" %s %s\n",it->ip, it->uri);
it = it->next;
}while(it != NULL);
}
你到底有什么问题? – Mat
你竟忘了提你的问题! –
问题是它没有工作。来自传递参数的数据不会显示在链接列表中。编译代码时不显示错误。 – George