gpt4 book ai didi

c - 查找指向字符数组的指针的索引

转载 作者:行者123 更新时间:2023-12-02 00:11:00 25 4
gpt4 key购买 nike

我正在使用这个 countof 宏

COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))

这给了我一个字符数组的大小,比如

char *ta[]={"asdf","qwer","zxcv"}

但是当我在函数范围内使用它时它不起作用。

int indexof(char *aword, char *arrayofwords[]){
int i; unsigned int ct=COUNT_OF( (*???) arrayofwords);
for (i=0 ; i<ct ;i++){
if (strcmp(aword,arrayofwords[i])==0){return i;}}
return -1;//not found
}

最佳答案

sizeof 被称为编译时 运算符。它只能计算大小可以预先确定的对象的大小。因此,当您向它传递一个指针时(数组在作为函数参数传递时会退化为指针),您只会得到指针的大小。

典型的安排是以 NULL 指针结束列表。有了这样的列表,您的函数可以这样写:

int indexof(char *aword, char *arrayofwords[]){
int i;
for (i=0 ; arrayofwords[i]!=NULL ;i++){
if (strcmp(aword,arrayofwords[i])==0){return i;}}
return -1;//not found
}

这看起来确实令人惊讶,因为以下确实有效:

#include <stdlib.h>

#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))

int main() {
char *ta[]={"asdf","qwer","zxcv"};
char *aword="qwer";
int i; unsigned int ct=COUNT_OF(ta);
for (i=0 ; i<ct ;i++){
if (strcmp(aword,ta[i])==0){return i;}}
return -1;//not found
}

这是因为数组 ta 定义在 sizeof 应用于它的相同范围内。由于 sizeof编译时 执行其计算,因此它可以使用编译器的符号表来准确发现为每个部分分配了多少空间。

但是,当您将它传递给一个函数时,就编译器而言,它不再是一个数组。 indexof 函数不能使用 sizeof 来发现传递的数组的大小,因为在这个函数内部它不是数组,它只是一个指针(char ** = = 字符 *[] == 字符 [][]).

使用COUNT_OF 宏的一种方法是让indexof 接受一个长度参数。然后您可以在调用中使用 COUNT_OF(只要相关数组在范围内定义)。

#include <stdlib.h>

#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))

int main() {
char *ta[]={"asdf","qwer","zxcv"};
char *word="qwer";
return indexof(word, ta, COUNT_OF(ta));
}

int indexof(char *aword, char *arrayofwords[], int length){

int i; unsigned int ct=length;
for (i=0 ; i<ct ;i++){
if (strcmp(aword,arrayofwords[i])==0){return i;}}
return -1;//not found
}

关于c - 查找指向字符数组的指针的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15426049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com