c - 将字符串数组作为字符指针传递

标签 c string

我一直在尝试将字符串数组传递给函数。虽然我知道执行此操作的其他过程,但我特别想确切地知道为什么这个特定代码不起作用

我尝试过以下方式

#include<stdio.h>

void check_number(char* str[])
{
    int sum=0;
    int i=0;
    while(str[0][i]!='/0')
    {
        char a='a';
        sum=sum+str[0][i]-(int)(a);
    }
    printf("number = %d ",sum);
}

int main()
{
    char* str[2];
    printf("Enter a string ");
    scanf("%s",str[0]);

    printf("Enter a string ");
    scanf("%s",str[1]);

    check_number(str);
    return 0;
}

最佳答案

这是此处发布的代码中的问题之一

char* str[2];

str两个字符指针的数组,即 str[0]str[1] 是字符指针,即它们需要使用有效地址进行初始化,但您尚未为它们分配内存。

scanf("%s",str[0]); /* No memory allocated for str[0] */
scanf("%s",str[1]); /* No memory allocated for str[1] */

在将数据扫描到其中之前,您需要为 str[0]str[1] 分配内存。例如

int main(void)
{
    char* str[2];
    for(int i = 0; i < 2 ; i++) {
        printf("Enter a string ");
        str[i] = malloc(MAX_BUF_SIZE); /*define this macro for no of bytes */
        scanf("%s",str[i]);
    }
    /* do some stuff */
    /* free dynamically allocated memory for each str[index] */
    return 0;
}

还有一个问题

while(str[0][i]!='\0') { /* '/0' --> '\0' */
    char a='a';
    sum=sum+str[0][i]-(int)(a); /* what you want to achieve here, please explain */
}

这个循环什么时候终止?应该有一个循环终止条件,否则它将无限循环。

关于c - 将字符串数组作为字符指针传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57240379/

相关文章:

c++ - 在 C++ 中以编程方式获取系统启动时间(Windows)

regex - 从 r 中的字符串中提取时间

string - 为什么我的 shell 脚本为每种情况提供相同的输出?

c - 总线错误: 10 While compiling C program

c - STM32 相同的 while 循环代码但编译为不同的汇编代码

c - freeaddrinfo 上发生了什么事?

python - 如何用模式替换字符串的一部分

java - JOptionPane 并从输入中获取文本

c++ - 如何获得 std::string 的准确长度?

c++ - 类的条件编译