gpt4 book ai didi

c - 这个将 char 数组转换为 int 数组的函数不起作用吗?

转载 作者:行者123 更新时间:2023-11-30 14:22:52 26 4
gpt4 key购买 nike

该程序应该通过从其 ascii 值中减去 97 将字符数组(字符串)转换为整数数组(输入应为小写,因为 a 的 ascii 值为 97)。因此,如果我输入字符串 abcd,我应该得到 0123,但我却以某种方式得到:012134513789。我不知道问题出在哪里。

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

void userEnter(int*pattern, int n);



int main(void)
{
int n, i;
printf("What is the length of the array: ");
scanf("%d",&n);
int pattern[n];
printf("Enter the char array: ");
userEnter(pattern, n);
printf("The int array is: ");
for(i=0;i<n;i++)
{
printf("%d",pattern[i]);
}
printf("\n");

}

void userEnter(int*pattern, int n)
{
char input[n];
scanf("%s", input);

int i;
for(i = 0; i < n-1; i++)
{
pattern[i] = input[i]-97;
}
}

最佳答案

char input[n];
scanf("%s", &input);

应该是

char input[n+1];
scanf("%s", input);

input 相当于 &input[0]

当遇到结束用户输入字符串的 nul 字符时,还应该退出 userEnter 中的 for 循环。例如类似的东西

char* p = input;
while (*p != '\0') {
*pattern = (*p) - 'a';
p++;
pattern++;
}

正如 KingsIndian 指出的那样,您还需要增加输入缓冲区的大小。目前,您溢出了该缓冲区并覆盖了循环计数器i

关于c - 这个将 char 数组转换为 int 数组的函数不起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13422523/

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