2013-12-20 2 views
-5

Я пишу небольшую небольшую программу как практику: ее можно добавить в векторы. Я получаю сообщение об ошибке из IDE, в котором говорится: «ошибка: индексированное значение не является ни массивом, ни указателем, ни вектором». Это происходит, когда я перехожу через цикл for и пользователь вводит некоторые данные типа float, используя функцию scanf(). Я отправлю код ниже, чтобы вы могли убедиться сами.Ошибка в коде, программирование на C

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

typedef struct 
{ 
    float xcomp; 
    float ycomp; 

}vectors; 

vectors initializeVector(vectors userVect, int length); 


int main() 
{ 


    /* This block determines the amount of vectors that will be added. 
    It will then create an array of vector structs the size of the amount being added. 
    Afterwards it will call a function that will grab the users data (vector information) and use 
    to add the vectors in the array.*/ 


    int amount; 
    printf("How many vectors would you like to add?\n"); 
    printf("AMOUNT: "); 
    scanf("%d", &amount); 
    vectors myvect[amount]; 


    initializeVector(myvect[amount],amount); //<-- This is a function call. 
    return 0; 

} 


vectors initializeVector(vectors userVect, int length) 
{ 
/* This function will go through the array of vectors and allow the user 
to input the components of each vector in the array.*/ 

printf("Enter the 'X' and 'Y' components of your vector\n"); 
int i; 
for(i=0; i<length;i++) 
{ 
    printf("%d", i+1); 
    printf(" vector:\n"); 
    printf("X: "); 
    scanf("%f", userVect[i].xcomp); // This line brings up the error 
    printf("\nY: "); 
    scanf("%f", userVect[i].ycomp); // this line brings up the error 


    } 



} 
+0

Почему пометка [tag: C++] then? Re-Tagged ... –

+0

векторы * userVect; userVect [я] -> xcomp; –

+1

Поскольку параметр userVect не является массивом. Вы не можете индексировать его. – OldProgrammer

ответ

0

Вам необходимо выделить массив векторов, используя malloc.

typedef struct 
{ 
    float x; 
    float y; 
}vectors; 

vectors initializeVector(vectors userVect[], int length); 

int main() 
{ 
    /* This block determines the amount of vectors that will be added. 
    It will then create an array of vector structs the size of the amount being added. 
    Afterwards it will call a function that will grab the users data (vector information) and use 
    to add the vectors in the array.*/ 

    int amount; 
    printf("How many vectors would you like to add?\n"); 
    printf("Count: "); 
    scanf("%d", &amount); 
    if(amount<1) { printf("error, need vector size %d > 0\n",amount); exit(1); } 
    vectors *vectarray = malloc(sizeof(vectors)*amount); //allocate the vector for the given vector size 
    if(!vectarray) { printf("error, cannot allocate vectorarray[%d]\n",amount); exit(2); } 
    initializeVector(vectarray,amount); //<-- This is a function call. 
    return 0; 
} 

Затем вам нужно передать этот массив (как указатель) на инициализаторе, и вы должны указать адрес вашего х, у компонентов, а не только компонентов.

vectors initializeVector(vectors userVect[], int length) //pass an array 
{ 
    /* This function will go through the array of vectors and allow the user 
    to input the components of each vector in the array.*/ 

    printf("Enter the 'X' and 'Y' components of your vector\n"); 
    int i; 
    for(i=0; i<length;i++) 
    { 
     printf("%d", i+1); 
     printf(" vector:\n"); 
     printf("X: "); 
     scanf("%f", &(userVect[i].x)); //scanf wants a pointer to the x component 
     printf("\nY: "); 
     scanf("%f", &(userVect[i].y)); //scanf wants a pointer to the y component 
    } 
} 
+0

Спасибо! Я собираюсь расшифровать это и посмотреть, что я получаю – Alberto93

0

Вы не можете статически выделять массив, передавая переменную (количество) в качестве ее размера. Чтобы сделать это, вам необходимо выделить его динамически, используя malloc.
Кроме того, индексы в массивах основаны на 0. Это означает, что вы можете получить доступ к своим элементам от 0 до размера-1. Если вы передадите myvector [size], вы попытаетесь прочитать после последнего элемента массива.

+0

Я довольно новичок в написании код, который означает, что я новичок в этом техническом языке. Если я правильно вас понимаю, вы говорите, что я не могу создать массив определенного размера, используя переменную, чтобы объявить размер? – Alberto93

+0

Вы не можете использовать переменную, потому что, когда вы статически выделяете массив, его размер должен определяться во время компиляции. Это означает, что при создании исполняемого файла компилятор резервирует для него определенный объем памяти. Поскольку в вашей программе размер массива будет определен во время выполнения, вам необходимо выделить его динамически. – Axel83

Смежные вопросы