【发布时间】:2019-04-29 03:22:18
【问题描述】:
我目前在将字符数组从我的主函数传递到某个计算数组中元素数量的函数时遇到问题。
我使用 getchar() 函数要求 2 个单独的字符串字符。
为了澄清,这是我的代码的 sn-p:
我尝试过使用 scanf to &myArray[0] 作为替代方法
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_LEN 20
int match(char s[], char t[] )
{
int i = 0;
int j = 0;
printf("begin: ivaL: %d, jval: %d\n", i, j);
while(s[i] != '\0')
i++;
while(t[j] != '\0')
j++;
printf("i val: %d, jval: %d ", i, j); /*J value is messed up, it prints 20+ when ive only typed 5 characters or so*/
}
int main()
{
int cur = 0;
char char1[ARRAY_LEN];
char char2[ARRAY_LEN];
char c;
char f;
printf("Enter char: ");
while((c=getchar())!=EOF && c!='\n')
{
char1[cur++] = c;
}
cur = 0;
printf("\n2nd Char: ");
while((f=getchar())!=EOF && f!='\n')
{
char2[cur++] = f;
putchar(f);
}
putchar('\n')
printf("Cur value: %d\n", cur); //here cur accurately prints the correct number of while loops done when counting the characters
match(char1, char2); /*here i tried to fetch the number of elements in char2 before i passed it to match function and in here char2 is showing correct value, something happens when i pass char2 to the match function*/
}
【问题讨论】:
-
为什么不
c=getchar())!=EOF && c!='\n'->(c=getchar())!='\n'? -
你不是 null 终止两个字符串。默认不添加空字符
-
我正在阅读“C 编程语言”并遵循相同的风格,如果我省略了 EOF 检查,但没有任何改变。
-
@sjsam 谢谢!这解决了我的问题。 :) 从来没有真正想过这个
-
当您没有在第一个 while 循环之后立即明确地执行
char1[cur]='\0'时,您不能执行s[i] != '\0'。第二个也是如此。