为什么表示两个数组之间差异的Difference输出为零?语言:C
#include <stdio.h>
#include <stdlib.h>
long int n=100000;
long int Difference=0;
long int q;
char *str1,*str2;
int main()
{
char string1[n];
char string2[n];
scanf("%ld",&q);
scanf("%s",&string1[q]);
scanf("%s",&string2[q]);
str1=string1;
str2=string2;
for(int i=0; str1[i]!=' ' && str2[i]!=' '; i++)
{
if(str1[i]!=str2[i])
Difference+=1;
}
printf("%ld",Difference);
return 0;
}
假设变量q用作内存偏移量,则需要将char指针str1和str2设置为数组中scanf存储从stdin读取的值的内存位置。
#include <stdio.h>
#include <stdlib.h>
long int n = 100000;
long int Difference = 0;
long int q;
char *str1,*str2;
int main()
{
char string1[n];
char string2[n];
scanf("%ld",&q);
scanf("%s",&string1[q]);
scanf("%s",&string2[q]);
// Set the char pointers to the address in the array
// q distance from the initial address of the array
// because you stored your input strings at that address
// and not at the beginning of the array in memory
str1 = string1 + q;
str2 = string2 + q;
for(int i=0; str1[i] != ' ' && str2[i] != ' '; i++)
{
if(str1[i] != str2[i])
Difference += 1;
}
printf("%ld", Difference);
return 0;
}