我正在尝试主持由数字组成的2数组--这是代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int n,i,j,k;
int a[n];
int b[n];
int ta=sizeof(a);
printf("Enter la taille du tableux: ");
scanf("%d", &n);
// taking input a
printf("Enter %d nombres: ",n);
for(i = 0; i < n; ++i)
{
scanf("%d", &a[i]);
}
// taking input b
printf("Enter %d nombres: ",n);
for(j = 0; j < n; ++j)
{
scanf("%d", &b[j]);
}
//a to b
for(k=0;k<ta;k++)
{
if(a[k] != b[k])
{
printf("Is ne sont pas identiques.\n");
exit(0);
}
else if(k == n-1)
{
printf("Ils sont identiques.\n");
}
}
}但是插入数组后没有得到比较,我做错了什么。
但是插入数组后没有得到比较,我做错了什么。
发布于 2022-10-30 15:40:39
当您比较数组a和数组b时,您的数组大小不正确。
int ta=sizeof(a);下面的代码给出了预期的输出
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int n,i,j,k;
int a[n];
int b[n];
//int ta=sizeof(a) calculate of array size is not correct
printf("Enter la taille du tableux: "); //Enter the array size
scanf("%d", &n);
// taking input a
printf("Enter %d integers: ",n);
for(i = 0; i < n; ++i)
{
scanf("%d", &a[i]);
}
// taking input b
printf("Enter %d nombre: ",n);
for(j = 0; j < n; ++j)
{
scanf("%d", &b[j]);
}
//a to b
for(k=0;k<(sizeof(a)/sizeof(a[0]));k++)
{
if(a[i] != b[i])
{
printf("are not identical\n");
exit(0);
}
}
printf("they are identical\n");
}输出:
Enter la taille du tableux: 3
Enter 3 integers: 1
2
3
Enter 3 nombre: 1
2
3
they are identical发布于 2022-10-30 16:01:24
您的代码有一个小问题,否则它是正确的。
改变这一点:
int n,i,j,k;
int a[n]; // n is not initialized
int b[n];
int ta=sizeof(a);
printf("Enter la taille du tableux: ");
scanf("%d", &n);对此:
int n,i,j,k;
int ta = sizeof(a);
printf("Enter la taille du tableux: ");
if (scanf("%d", &n) != 1) { /* handle errors */ }
int a[n]; // now n is initialized
int b[n];问题是,n是声明的,但一开始从未分配过。这意味着,n可以是这个内存中的任何值。这称为未初始化内存。下面是一个关于这一点的快速演示:
int main() {
int arr[256];
for (int i = 0; i < 256; i++) {
printf("%10d%c", arr[i], (i + 1) % 16 == 0 ? '\n' : ' ');
}
}https://stackoverflow.com/questions/74254027
复制相似问题