[英]Making Test cases?
我是C語言的新手,我正在嘗試制作測試用例以測試節點交換,但不知道如何制作測試用例。 如果有人可以給我一個例子,那就太好了。 謝謝
有人可以告訴我在交換功能中我做錯了什么,因為這些值沒有被交換?
#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 2\n", nodeA.data);
printf("nodeB has value %d, should be 1\n", nodeB.data);
swap函數是錯誤的,像這樣修改它
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
swap(int ** a,int ** b)`
如同
int foo(int a) {
a = 123;
}
int a = 1;
foo(a);
從函數a返回時,對foo
的調用不會更改參數,只是將其復制然后修改,然后仍具有其原始值。
int foo(int* a)
{
*a = 1;
}
變化不是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,我認為它在軟件中心中。
至於您的代碼實際上有什么問題呢? 好吧,我不會告訴您,因為從長遠來看,這不會幫助您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.