2014-02-28 3 views
0

그래서이 코드포인터를 배열로 사용 하시겠습니까?

int *userInput; //array place holder 
//int max; //Max variable for later use in comparisons 
int start = 0; //inital starting point value for loops 
int endUserInput; //used to find the total number input 




printf("You may enter up to a max of 50 integer values, Please enter the first value: "); 

//loop collects the user inputs 
/* Using a while loop to check for data to be true in what is entered 
to spot when the data becomes false when a letter is entered*/ 
while (scanf("%d", &userInput[start]) == 1) { 
    //If statement entered to catch when the total is met 
    if (start == 49) { 
     break; 
    } 
    start = start + 1; 
    //Print statement to let user know what value they are at and how to end input 
    printf("Enter next value %d or enter C to calculate: ", start + 1); 

} 

가 IT 메모리 오류로 충돌 PC에서 내 MBP 컴파일러에서 실행하지만 데브에 있나요? 오류가 int *userInput 신고입니다. 배열에 특성을 지정하지 않고이 문제를 해결하려면 어떻게해야합니까?

+1

'userInput'에 대한 메모리를 할당해야합니다. – jxh

+0

오류 메시지에 대해 자세히 알려주십시오. –

답변

0

int userInput[50]; 

int *userInput; 

를 교체하고 코드가 작동합니다.

문제는 배열에 대한 포인터를 만들었지 만 포인터가 가리 키기위한 메모리를 생성하지 않았다는 것입니다. 위의 솔루션은 스택에 50 개의 정수를위한 공간이 있고, userInput을 가리키는 것을 보장합니다. 이렇게하면 userInput이 가리키는 메모리에 액세스 할 때 사용할 수있는 유효한 메모리가 준비되어 있습니다. 기존 코드에는 그러한 메모리가 없으므로 포인터가 가리키는 포인터가 무엇이든간에 포인터를 가리 키도록 컴퓨터가 시도합니다 (초기화되지 않았기 때문에 아무데도 없거나 일부 코드, 프로그램의 다른 데이터 등). .

2

아주 중요한 것을 포함 할 수있는 할당되지 않은 메모리를 덮어 쓰는 중입니다. 50 개의 정수를 저장할 충분한 공간을 할당하고 userInput을 해당 값으로 설정해야합니다.

int *userInput = malloc(sizeof(*userInput)*50); 

사용을 마치면 free(userInput)으로 전화하는 것을 잊지 마십시오.

+2

'malloc'의 결과를 캐스팅하지 마십시오. 'int * userInput = malloc (50 * sizeof (* userInput));'이 더 강력합니다. –

관련 문제