【发布时间】:2015-03-27 16:41:25
【问题描述】:
我正在尝试查找字符串 1(s1).. 的长度,但它给出的值为 0,并且输入 s1 = "HELLO",因为此错误无法执行我所在的 for 循环使用字符串 1 的长度。
以下是代码...在 gcc 版本 4.9.1 (Ubuntu 4.9.1-16ubuntu6) 中可以正常工作,但在在线编译器中不能正常工作(gcc 4.9.2,C99 标准)
/*To check if common characters are present in two strings*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdio_ext.h>
#define SIZE 100
int main() {
int m, i, j, t, len1;
char *s1, *s2;
scanf("%d", &t); //No. test cases
__fpurge(stdin);
for(m = 0; m < t; m++)
{
int res = 0;
s1 = (char *)malloc( SIZE * sizeof( char ));
s2 = (char *)malloc( SIZE * sizeof( char ));
fgets(s1, SIZE, stdin);
fgets(s2, SIZE, stdin);
*(s1 + strlen(s1) - 1) = '\0';
*(s2 + strlen(s2) - 1) = '\0';
len1 = strlen(s1); // len1 is storing as 0
printf("%d", len1 );
for (i = 0; i < strlen(s1); i++)
{
for (j = 0;j < strlen(s2); j++)
{
if ( *(s1 + i) == *(s2 + j) )
res = 1;
}
}
if(res == 1)
printf( "YES\n" );
else
printf("NO\n");
}
return 0;
}
【问题讨论】:
-
什么是 s1 定义后的转储?
-
SIZE定义为什么?我希望不是5!!5不足以容纳"HELLO"...您需要考虑'\0'终止符以及换行符。 -
我将
10用作SIZE,您的代码对我有用... -
@Jongware 为什么要定义这么奇怪的东西?使用像
10这样的数值来定义字节数或字符数。