ошибка компоновки в блоке кода для функции - PullRequest
0 голосов
/ 07 июня 2019

Я хочу сделать простую переменную для номера цикла для цикла, поэтому я попробовал свой код

int size,counter,marks[size];
scanf("enter %d/n",&size);
for(counter=0;counter<size;counter++)
{
    scanf("%d",&marks[counter]);
}

и скомпилирован без ошибок, но при запуске он просто показывает "process returned -1073741571 <0*c00000FD>.

, поэтому я попробовал gets функцию, и она показывает "too many arguments to function 'gets' ".

int size;
int counter;
int marks[size];
scanf("enter %d/n",&size);
for(counter=0;counter<size;counter++)
{
    gets("%d",&marks[counter]);
}

Я использую code :: blocks 17.12 и компилятор gnu.

Ответы [ 3 ]

1 голос
/ 07 июня 2019

Пожалуйста, не используйте gets. Это опасно .

Что касается вашей ошибки в примере scanf, первая проблема - это строка

int size,counter,marks[size];

, которая объявляет marks с неинициализированным size значение.Попробуйте сначала инициализировать size, а затем объявить массив marks.

Ваша вторая проблема - scanf строка форматирования.Используйте scanf, чтобы прочитать отформатированный ввод, а не выводить подсказку.Для этого используйте puts или printf.

Вот полный пример:

#include <stdio.h>

int main(void) {  
    int size;
    printf("Enter a size value: ");
    scanf("%d", &size);
    int marks[size];

    for (int i = 0; i < size; i++) {
        printf("Enter element %d: ", i);
        scanf("%d", &marks[i]);
    }

    printf("You entered: ");

    for (int i = 0; i < size; i++) {
        printf("%d ", marks[i]);
    }

    puts("");
    return 0;
}

Вот примерный прогон:

Enter a size value: 4
Enter element 0: 88
Enter element 1: 77
Enter element 2: 66
Enter element 3: 55
You entered: 88 77 66 55

Если вы пишете ANSI C-совместимый код вы можете использовать динамическую память с malloc:

#include <stdio.h>
#include <stdlib.h>

int main(void) {  
    int i, size, *marks;
    printf("Enter a size value: ");
    scanf("%d", &size);

    if (size < 1) {
        fprintf(stderr, "Invalid size specified\n");
        exit(1);
    }

    marks = malloc(size * sizeof(int));

    if (!marks) {
        fprintf(stderr, "malloc failed\n");
        exit(1);
    }

    for (i = 0; i < size; i++) {
        printf("Enter element %d: ", i);
        scanf("%d", &marks[i]);
    }

    printf("You entered: ");

    for (i = 0; i < size; i++) {
        printf("%d ", marks[i]);
    }

    free(marks);
    puts("");
    return 0;
}
1 голос
/ 07 июня 2019

size может иметь любое значение, когда массив marks выделен, потому что он не инициализирован.Массив может быть меньше введенного размера, поэтому отметки сохраняются в нераспределенной памяти, что дает вам ошибку.

Это возможное решение, но оно не соответствует строгому стандарту ISO C90.Предположительно, ваш CodeBlocks использует GCC, который принимает массивы переменной длины и смешанные объявления и код.

#include <stdio.h>

int main(void) {
    int size;
    printf("enter size: ");
    scanf("%d",&size);
    int marks[size];
    int counter;
    for (counter = 0; counter < size; counter++) {
        scanf("%d", &marks[counter]);
    }
    for (counter = 0; counter < size; counter++) {
        printf("%d: %d\n", counter, marks[counter]);
    }
    return 0;
}

Кстати, не говорите «ошибка сборки», если у вас есть ошибка во время выполнения.; -)

1 голос
/ 07 июня 2019

size должно иметь определенное значение, например:

#include <stdio.h>
int main()
{
    int size;
    size = 5; // size must be constant
    int counter, marks[size];
    for (counter = 0; counter < size; counter++)
    {
        scanf("%d", &marks[counter]);
    }
    //Printing it returns correct values:
    for (counter = 0; counter < size; counter++)
    {
        printf("%d\n", marks[counter]);
    }
}

Вместо этого вы можете ввести его значение от пользователя, если хотите.

Однако, если по какой-то причине после определения массива должно быть определено size, используйте указатели:

#include <stdio.h>
#include "stdlib.h"
int main()
{
    int size;
    int counter, *marks;
    size = 5; //declared after the array
    marks = (int *)malloc(size * sizeof(int));
    for (counter = 0; counter < size; counter++)
    {
        scanf("%d", &marks[counter]);
    }
    //Printing it returns correct values:
    for (counter = 0; counter < size; counter++)
    {
        printf("%d\n", marks[counter]);
    }
    //Don't forget to free the array in the end
    free(marks);
}
...