2014-02-14 4 views
0

Сначала я хочу начать говорить, что я студент, и новый для кодирования. Итак, я заранее извиняюсь за свою общую нехватку знаний в этом департаменте.сохранение целых чисел в массиве 2d с переменными

Я пытаюсь написать код, который будет читать целые числа и хранить их в многомерном массиве. Целые числа - это точки на графике, x & y значения. Кроме того, я хочу, чтобы размер массива был переменной, которую вводит пользователь (как в количестве точек, которые пользователь вводит - точки [numPoints] [2]). Это то, что я до сих пор:

#include <stdio.h> 
int main() 
{ 

int numPoints=0, row, colm; 
int points[numPoints][2]; 





printf("This program will read in a number of points, and calculate the distance between them.\n"); 
printf("It will also calculate the total distance between the first point, and the last point.\n"); 
printf("\nHow many points will you be entering?\n"); 
scanf(" %d", &numPoints); 
printf("Please enter each point individually.\nExample(x & y values shown):\nx y\n3 5\n-2 10\netc...\nPlease enter your points now (press 'Enter' after each point):\n"); 
for (row = 0; row<numPoints; row++) 
{ 
    for (colm = 0; colm<2; colm++) 
    { 
      scanf("%d", &points[row][colm]); 
    } 
} 
printf("These are the points recorded:\n"); 
for (row = 0, colm=0; row<numPoints; row++) 
{ 
    printf("(%d,%d)\n", points[row][colm],points[row][colm+1]); 
} 

return 0; 
} 

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

This program will read in a number of points, and calculate the distance between them. 
It will also calculate the total distance between the first point, and the last point. 

How many points will you be entering? 
4 
Please enter each point individually. 
Example(x & y values shown): 
x y 
3 5 
-2 10 
etc... 
Please enter your points now (press 'Enter' after each point): 
1 2 
3 4 
5 6 
7 8 
These are the points recorded: 
(1,2) 
(3,4) 
(6,31) 
(1,8) 
Program ended with exit code: 0 

Может ли кто-нибудь сказать мне, что я делаю неправильно?

Спасибо

+0

Вы объявляете пустой массив, смотрите на две строки после 'main()' -> 'points [0] [2]'. Вы должны либо объявить переменную после того, как пользователь внесет правильное измерение, либо объявит указатель '** ptr' для' malloc() '. Попробуйте поместить эту строку 'int points [numPoints] [2];' сразу после первого 'scanf' – yeyo

+0

http://stackoverflow.com/questions/9722632/what-happens-if-i-define-a-0-size -array-in-cc – Jeyaram

+0

Ваш код отлично работает на моей машине ...., я использую 'MingW' на windows xp и' gcc' 4.7.2; Хотя я бы рекомендовал использовать структуру для хранения точек, а затем добавить их в список ссылок или очередь. – shengy

ответ

0

Я надеюсь, что этот код поможет вам:

#include <stdio.h> 
    int main() 
{ 

    int numPoints =0,row, colm; 
    int points[10][2]; 

    printf("This program will read in a number of points, and calculate the distance between them.\n"); 
    printf("It will also calculate the total distance between the first point, and the last point.\n"); 
    printf("\nHow many points will you be entering?\n"); 
    scanf(" %d", &numPoints); 
    printf("Please enter each point individually.\nExample(x & y values shown):\nx y\n3 5\n-2 10\netc...\nPlease enter your points now (press 'Enter' after each point):\n"); 

for (row = 0; row < numPoints; row++) 
{ 
    for (colm = 0; colm<2; colm++) 
    { 
      scanf("%d", &points[row][colm]); 
    } 
} 
printf("These are the points recorded:\n"); 
for (row = 0, colm=0; row<numPoints; row++) 
{ 
    printf("(%d,%d)\n", points[row][colm],points[row][colm+1]); 
} 

return 0; 
} 
0

движение

int points[numPoints][2]; 

к после

scanf(" %d", &numPoints); 

например
scanf(" %d", &numPoints); 
int points[numPoints][2]; 
Смежные вопросы