C - Массив возвращает разные значения из одного и того же элемента при помещении в переменную - PullRequest
0 голосов
/ 25 января 2020

Я очень новичок в программировании. Короче говоря, моя проблема:

arr[0]=1 arr[1]=2 arr[2]= -4
printf("\n Element 0 when in array: %d\n", arr[0]); // Prints 1 as it should
arr[0] = a;
printf(" Element 0 assigned to variable a: %d", a); /* Prints 67 ?? (Elements 1 and 2 
are printed as 0 when assigned different variables.) */

Я хочу, чтобы моя переменная "a" возвращала то же значение, что и arr [0] (а затем делаю это еще для двух переменных для arr [1] и arr [2])

У меня есть текстовый файл с несколькими цифрами под названием «Dane.txt», его содержимое - «1, 2, -4,».

Вот полный код, в котором я пытаюсь решить математическую задачу с помощью ввода, взятого из файла .txt (я получил большую часть из здесь ):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){

    // Initializing the file pointer
    FILE *fs;

    char ch, buffer[32];
    int i = 0, arr[100], j = 0;
    int a, b, c, arr2[3];

    // Openning the file with file handler as fs
    fs = fopen("Dane.txt", "r");                    // "Dane.txt" contents: 1, 2, -4,

    // Read the file unless the file encounters an EOF
    while(1){
        // Reads the character where the seeker is currently
        ch = fgetc(fs);

        // If EOF is encountered then break out of the while loop
        if(ch == EOF){
            break;
        }

        // If the delimiter is encounterd(which can be
        // anything according to your wish) then skip the character
        // and store the last read array of characters in
        // an integer array
        else if(ch == ','){

            // Converting the content of the buffer into
            // an array position
            arr[j] = atoi(buffer);

            // Increamenting the array position
            j++;

            // Clearing the buffer, this function takes two
            // arguments, one is a character pointer and 
            // the other one is the size of the character array
            memset(buffer, 0, 32);

            // clearing the counter which counts the number
            // of character in each number used for reading
            // into the buffer.
            i = 0;

            // then continue
            continue;
        }
        else{

            // reads the current character in the buffer
            buffer[i] = ch;

            // increamenting the counter so that the next
            // character is read in the next position in 
            // the array of buffer
            i++;
        }
    }
    for(i = 0; i < j; i++){
        arr2[i] = arr[i];
        printf("Number [%d]: %d\n", i, arr[i]);
        printf("%d\n", arr[i]);
    }

    printf("\n Element 0 when in array: %d\n", arr[0]); // Returns 1 as it should
    arr[0] = a;
    printf(" Element 0 assigned to variable a: %d", a); // Returns 67 ??
}

1 Ответ

0 голосов
/ 25 января 2020

В вашем коде нет места, где бы вы присваивали какое-либо значение для a, поэтому, когда вы печатаете значение a, вы получаете тот мусор, который оказался в этой области памяти.

arr[0] = a;

Это задание. С левой стороны находится переменная, присвоенная от до , arr[0]. Правая часть - это значение, присвоенное ему. Если вы не уверены в этом, вы можете sh изучить хороший справочный раздел C по lvalues ​​и rvalues.

...