在C中崩溃编译的程序

时间:2013-01-01 13:54:03

标签: c

我有一个程序,用于将10个整数从一个数组复制到另一个数组。它正在编译而没有任何错误。它如下: -

/* Program to copy a string from one array to another array and print the second array */
#include<stdio.h>
#include<conio.h>
#define MAX 10
void main()
{
    int s[MAX]; // Original array
    int c[MAX]; // Array which contains the copied contents of s[MAX]
    int i;
    printf("Enter the string of 10 characters");
    for(i=0;i<MAX;i++)  // Storing elements in the original array
    {
        scanf("%d",s[i]);
    }
    for(i=0;i<MAX;i++)
    {
        printf("%d",s[i]);
    }
    printf("\n");
    for(i=0;i<MAX;i++)  /*Copying the elements from the original array into the duplicate array*/
    {
        c[i]=s[i];
    }
    for(i=0;i<MAX;i++) //Printing the duplicate array
    {
        printf("%d",c[i]);
    }
}

它甚至不打印原始数组。更不用说复制数组,这是程序的后半部分。

4 个答案:

答案 0 :(得分:6)

scanf("%d",s[i]);应为scanf("%d",&s[i]);

答案 1 :(得分:4)

您忘记了&中的scanf。代码应为:scanf("%d",&s[i]);。为什么?您只需向函数提供变量的地址即应更改哪个值。如果没有指针,该函数将无法更改该值。

示例:

int function1(int a) {
    a = 10;
}

int function2(int* a) {
    *a = 20;
}

(...)
int a = 5;
function1(a);
printf("%d\n", a); /* a is still 5 */
function2(&a);
printf("%d\n", a); /* a is now 20 */

答案 2 :(得分:2)

您应该在&

期间使用scanf运算符
scanf("%d",&s[i]);

答案 3 :(得分:2)

函数scanf需要一个指向整数的指针作为参数。由于s[i]返回数组s中索引i处的整数值而不是指向它的指针,scanf会尝试将扫描的值存储到无效的内存位置,从而导致程序崩溃。

使用&s[i]来提供scanf指针。