用c语言中的assert检查strncpy函数
我需要编写c程序来比较两个字符串,而不使用strncpy(),然后在另一个函数中检查它是否与assert()一起工作 在我的代码中,通过检查指针用c语言中的assert检查strncpy函数,c,function,assert,strncpy,C,Function,Assert,Strncpy,我需要编写c程序来比较两个字符串,而不使用strncpy(),然后在另一个函数中检查它是否与assert()一起工作 在我的代码中,通过检查指针assert(*str2==*“comp”)我只检查第一个字母,其他什么都不检查。因此,即使有另一个以c开头的单词,它也会起作用 char initialize_n(char str1[], char str2_n[], int n) { //initialize a string from the (at most) n first chara
assert(*str2==*“comp”)代码>我只检查第一个字母,其他什么都不检查。因此,即使有另一个以c开头的单词,它也会起作用
char initialize_n(char str1[], char str2_n[], int n)
{
//initialize a string from the (at most) n first characters of another string
int i = 0;
for(i = 0; i < n; i++)
{
str2_n[i] = str1[i];
}
str2_n[i] = '\0';
}
void test_initialize_n(){
char str1[100] = "computer";
char str2[100];
initialize_n(str1, str2, 4);
assert(*str2 == *"comp");
}
char initialize_n(char str1[],char str2_n[],int n)
{
//从另一个字符串的前n个字符(最多)初始化一个字符串
int i=0;
对于(i=0;i
如何使用assert正确地检查它?因此,如果没有gcc
扩展,您就不能将其放入assert主体,因为这样做的函数对您是禁止的
您需要做的是编写自己的比较函数并调用它。框架如下:
int prefix_equals(const char *left, const char *right, int nleft, int nright)
{
if (nleft != nright) return 0;
/* Use the same for loop here you have in initialize_n */
if (left[i] != right[i]) return 0;
return 1; /* If you got all the way through they're equal */
}
assert(prefix_equals(str2, "comp", 4, 4));
根据我的经验,这种方法最有用的形式实际上有两个长度参数,以避免调用方在调用点中遇到麻烦。在assert
级别上,它似乎是错误的,但当您达到几千行时,它并没有错误。这是否回答了您的问题@超级明星:不,不是。OP不需要使用strcmp。@约书亚OP没有提到strcmp。