【问题标题】:In C, How do you access elements in an array through a double pointer在C中,如何通过双指针访问数组中的元素
【发布时间】:2018-03-24 20:16:38
【问题描述】:

我正在尝试为我的班级编写一个程序,但我无法开始,因为我不知道如何访问函数的参数元素。一个 char 数组被传递给函数,如下所示:

RPN_calculator(input1)

其中 input1 是一个指向数组的指针,函数的开头是这样的

int RPN_calculator(const char** input)
{
    int n = strlen(*input);
    printf("LENGTH OF INPUT: %d\n", n);
    return 0;
}

我试图找到数组的长度,然后遍历数组,但是我尝试过的任何东西都没有打印出正确的数组长度,而且我似乎无法弄清楚如何访问任何元素'input' (打印语句仅用于调试)

编辑: 即使我将 n 计算为:

int n = sizeof(*input)/sizeof(*input[0]);

没用

【问题讨论】:

  • 欢迎来到 Stack Overflow。请尽快阅读AboutHow to Ask 页面。您在创建 MCVE (minimal reproducible example) 时做出了不错的尝试,但是您省略了显示传递给函数的 input1 变量是如何定义和填充的代码,这可能非常重要。如果你有char input1[256];,那么你显示的调用与你显示的函数不匹配,所以你使用了其他东西——这很重要。
  • 向我们展示您如何声明input1 和代码的其他相关部分。
  • 您的代码中没有数组。 input 是一个指针,应该这样对待。仔细阅读。
  • 对字符串进行操作的函数通常接受char *。在这种情况下使用char ** 是不寻常的,在这里可能没有必要。
  • 由于对数组一无所知,因此无法从指向它的指针计算出它有多少元素。在这种情况下经常使用的一种约定是数组的最后一个元素是 NULL 字符指针。你自己写过调用RPN_calculator的代码吗?

标签: c arrays pointers double-pointer


【解决方案1】:

我希望这个源代码可以帮助你解决这个问题。这是一个简单的示例程序,演示了如何逐个字符地访问任何字符串以及如何查找字符串的大小。

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>

#define NUMBER_OS_CHAR_STRINGS  5 

/* Here input is a pointer to an array of strings */
const char *input[NUMBER_OS_CHAR_STRINGS] = {
    "ONE", /*string0. string[0][0] = 'O' -> first element of string0 - O
                        string[0][1] = 'N' -> second element of string0 - N
                        string[0][2] = 'E' -> third element of string0 - E  */ 

    "TWO", /*string1*/ 
    "THREE", /*string2*/
    "FOUR", /*string3*/
    "FIVE", /*string4*/
};


int RPN_calculator(const char **input);
void itterate (const char **input, int choosen_string); 

int main(void) {

    int string_to_itterate = 0;

    RPN_calculator(input);

    printf("Select the string which you would like to print char by char:\n");
    scanf("%d", &string_to_itterate);

    itterate(input, string_to_itterate);

    return(0);
}

int RPN_calculator(const char** input)
{
    int i;

    for (i = 0; i < NUMBER_OS_CHAR_STRINGS; i++)
    {
        int n = strlen(input[i]);
        printf("LENGTH OF INPUT: %d\n", n);
    }
    return 0;
}

/*Simple example function which itterates throught the elements of a chossen string and prints them 
one by one.*/
void itterate (const char **input, int choosen_string)
{
    int i;
    /*Here we get the size of the string which will be used to define the boundries of the for loop*/
    int n = strlen(input[choosen_string]);

    for (i = 0; i < n; i++)
    {
        printf("The %d character of string[%d] is: %c\n",i+1, choosen_string, input[choosen_string][i] ); /*Here we print each character of the string */
    }
    return;
}

【讨论】:

    猜你喜欢
    • 2014-02-19
    • 2016-07-13
    • 1970-01-01
    • 2012-07-30
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多