我是C的新手,我正在尝试制作测试用例来测试节点交换,但不知道如何制作测试用例。如果有人能给我举个例子,那就太好了。Thx
有人能告诉我我在交换函数中做错了什么吗?因为值没有交换?
#include <stdio.h>
#include <stdlib.h>
struct lnode {
int data;
struct lnode* next;
};
void swap(int* a, int* b );
int main()
{
int x = 10;
int y = 14;
swap(&x, &y);
swapNodes(x, y);
getchar();
return 0;
}
void swap(int* a, int* b )
{
int* temp;
temp = a;
a = b;
b = temp;
printf("x= %d y= %d",*a,*b);
}
void swapNodes(struct lnode* n1, struct lnode* n2)
{
struct lnode* temp;
temp = n1->next;
n1->next = n2;
n2->next = temp;
}
从最简单的测试用例开始。需要两个节点才能进行节点交换。只需声明两个节点结构,为每个节点分配不同的值,交换节点,然后打印结果。类似这样的东西:
struct lnode nodeA, nodeB;
nodeA.data = 1;
nodeB.data = 2;
swapNodes(&nodeA, &nodeB);
printf("nodeA has value %d, should be 2n", nodeA.data);
printf("nodeB has value %d, should be 1n", nodeB.data);
交换函数错误,像这样修改
void swap(int* a, int* b )
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf("x= %d y= %d",*a,*b);
}
那么您正在更改值,因为您无法使用这些参数更改a
和b
所指向的内容
它不起作用的原因是这个
void swap(int* a, int* b )
{
int* temp; // pointer
temp = a; // temppointing to same as a is pointing to
+------------+
temp -> | some value |
+------------+
a = b; // a now pointing to same as b is pointing to
+------------------+
a -> | some other value |
+------------------+
b = temp; // b now pointing to same as temp pointing to, a
+------------+
b -> | some value |
+------------+
但是当您从函数返回时,指针保持不变。如果要更改a
和`b point to you need to have arguments
交换的内容(int**a,int**b)`
类似于
int foo(int a) {
a = 123;
}
int a = 1;
foo(a);
对foo
的调用不会更改参数,它只是被复制然后修改,当从函数a返回时仍然具有其原始值。
int foo(int* a)
{
*a = 1;
}
不是改变a
指向的值,而是改变a仍然指向同一点
int foo(int**a )
{
*a = malloc(sizeof(int)); // changes where a points to
...
}
进行测试非常容易。使用预处理器宏,您可以毫不退缩地执行此操作。例如,您有:
int main()
{
int x = 10;
int y = 14;
swap(&x, &y);
swapNodes(x, y);
getchar();
return 0;
}
使其
#define TEST
#ifndef TEST
int main()
{ //regular running
int x = 10;
int y = 14;
swap(&x, &y);
swapNodes(x, y);
getchar();
return 0;
}
#endif
#ifdef TEST
int main()
{
//test your code!
return 0;
}
#endif
#
是制作C时的指令。#define TEST
的意思是"我们处于测试模式"。#ifndef TEST
的意思是"如果我们不测试"。#ifdef TEST
的意思是"如果我们正在测试"。我们本可以用
} //end regular main
#else
int main() //begin test main
但这其实并不重要。请注意,#define
行位于所有#ifdef
和#ifndef
行之前。
如果这仍然没有帮助,你可能想尝试使用预处理器宏来覆盖打印语句
#define DEBUG
#ifdef DEBUG
#include <stdio.h>
#endif
...
void myFunc(){
int x = 0;
#ifdef DEBUG
printf("%d", x);
#endif
}
如果你真的想,你可以在编译过程中定义一些东西(这被认为是更花哨的)。
gcc -DDEBUG -DTEST -o swap_test swap.c
如果这些对您没有帮助,您应该检查GDB来调试您的代码。如果你使用的是Ubuntu,我认为它在软件中心。
至于你的代码到底出了什么问题?好吧,我不会告诉你,因为从长远来看,这对你没有帮助。