我正在尝试为我的课程编写一个程序,但我无法开始,因为我不知道如何访问函数的参数元素。 char数组传递给函数,如下所示:
RPN_calculator(input1)
其中input1是一个指向数组的指针,函数就像这样开始
int RPN_calculator(const char** input)
{
int n = strlen(*input);
printf("LENGTH OF INPUT: %d\n", n);
return 0;
}
我试图找到数组的长度,然后遍历数组,但我尝试的任何东西都没有打印出阵列的正确长度,我似乎无法弄清楚如何访问输入'的任何元素(print语句仅用于调试)
编辑: 即使我计算n为:
int n = sizeof(*input)/sizeof(*input[0]);
它不起作用
答案 0 :(得分:0)
我希望此源代码可以帮助您解决问题。这是一个简单的示例程序,演示如何逐个字符地访问任何字符串,以及如何查找字符串的大小。
#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;
}