C - 指向数组中索引号的指针

标签 c arrays pointers

我知道我必须忽略一些简单的事情。我有一个程序可以让用户通过显示每个探测器的索引来观察不同的搜索算法如何探测数组。我有一个传递给排序算法函数的指针,应该为它分配找到搜索数字的索引号。然后在另一个函数中使用该指针来显示在哪个索引中找到了该值(如果找到的话)。

我在显示找到值的索引的函数中遇到运行时错误。(search_results)(当搜索到的数字不在数组中时,程序运行正常。)它一定是一个简单的错误,但我认为一组新的眼睛可能会有所帮助。

一切都是 int,除了 found_statuschar

这是 main() 代码。 (必要的东西)

    int *p_return_index = NULL;

/* Fill arrays with data                                           */
fill_array(seq_data, max_index);
fill_array(prob_data, max_index);
fill_array(bin_data, max_index);

while(printf("\n\n\nEnter an integer search target (0 to quit): "),
        scanf("%d", &searched_number), searched_number != 0)
{
    printf("\n\n");
    printf("\nOrdered Sequential Search:");
    show_data(seq_data, max_index, searched_number);
    if(ordered_seq_search(seq_data, max_index, searched_number, p_return_index) == 1)
    {
        found_status = 'S';
        search_results(found_status, p_return_index);
    }
    else
    {
        found_status = 'U';
        search_results(found_status, p_return_index);
    }

这是指针传递给指定索引的地方。

int ordered_seq_search(int array[], int max_index, int searched_number, int *p_return_index)
{
int index = 0;

printf("\n   Search Path: ");
while (index < max_index && searched_number != array[index] &&
         searched_number > array[index])
{
    printf("[%2d]", index);
    index++;
}

if(searched_number == array[index] != 0)
{
    p_return_index = &index;
    return 1;
}
else
    return 0;
}

这就是错误发生的地方。

void search_results(char found, int *p_return_index)
{
printf("\nSearch Outcome: ");
if(found == 'S')
    printf("Successful - target found at index [%2d]", *p_return_index);
            //I get the error at the line above.
if(found == 'U')
    printf("Unsuccessful - target not found");
if(found != 'S' && found != 'U')
    printf("Undetermined");
return;
}

如果有人能找出问题所在,那将对我有很大帮助。如果您需要更多信息,请发表评论,我会尽快回复。

最佳答案

p_return_index 初始化为 NULL。

使用 int p_return_index[1];

比 search_results(...)

if(searched_number == array[index] != 0) {
  *p_return_index = index;

关于C - 指向数组中索引号的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20133177/

相关文章:

c - 如何检查 char 中是否存在 EOF?

arrays - 快速限制数组大小

c - 数组循环不起作用

c - 奇怪的分段默认

c - 应用程序因指针、头文件和结构数组而崩溃

在 C 中从 main 调用 void* 函数

c - 使用 Swig 将字符串列表从 C 函数发送到 TCL 进程

c - 为什么我的 BST 根指针由于某些未知原因而改变?

python - numpy 2d 区域的快速随机到唯一重新标记(无循环)

java - 为什么可以在 Java 中通过引用来比较不兼容的类型?