Reputation: 75
I've written this code to read values from a file, and if a read value is a ";" is, all values that occurred up to now and were written in a string should be written into a field of a pointer array
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <windows.h>
#define SIZE_STRINGS 100
#define SIZE_ZS 15
int index_drei;
char *laenge_drei[SIZE_STRINGS];
char* string_to_pointer(char []);
void laengen_block_nach_siegen_ordnen();
void spielweg_nach_laenge_des_spieweges_ordnen(bool spieler)
{
int i,
laenge,
index_zs;
char buchstabe,
zs[SIZE_ZS],
zs2[SIZE_ZS],
*zs_p;
bool akt_laenge_auslesen;
FILE * fp;
if(spieler)
fp = fopen("Anlagen\\spielweg_spieler.txt", "r"); //Datei öffnen
else
fp = fopen("Anlagen\\spielweg_ai.txt", "r"); //Datei öffnen
akt_laenge_auslesen = true;
index_drei = 0;
laenge = 0;
index_zs = 0;
for(i = 0; i < SIZE_ZS; i++)
{
zs[i] = 0;
}
if(fp == NULL)
{
}else
{
while((buchstabe = fgetc(fp))!=EOF)
{
zs[index_zs] = buchstabe;
index_zs++;
if(akt_laenge_auslesen == true && buchstabe == '-')
akt_laenge_auslesen = false;
else if(akt_laenge_auslesen)
laenge = buchstabe - '0';
else if(buchstabe == ';')
{
if(laenge == 3)
{
laenge_drei[index_drei] = string_to_pointer(zs);
/*Firts value*/
strcpy(zs2, laenge_drei[0]);
printf("%s", zs2);Sleep(1000);
index_drei++;
}
akt_laenge_auslesen = true;
laenge = 0;
index_zs = 0;
for(i = 0; i < SIZE_ZS; i++)
{
zs[i] = 0;
}
}
}
/*Second value*/
strcpy(zs2, laenge_drei[0]);
printf("%s", zs2);Sleep(1000);
fclose(fp);
}
}
char* string_to_pointer(char string[])
{
return string;
}
If I write the value from "length_drei [0]" with strcpy in string "zs2", I get:
Upvotes: 0
Views: 103
Reputation: 150
You aren't allocating any memory for the string segments you're trying to save in laenge_drei
. At the end of the loop, each index of laenge_drei
contains a reference to zs
and therefore the last string processed.
if(laenge == 3)
{
laenge_drei[index_drei] = strdup(zs);
printf("%s", laenge_drei[index_drei]);
sleep(1000);
index_drei++;
}
Change strcpy(zs2, laenge_drei[0])
to strcpy(zs2, laenge_drei[index_drei])
if you're trying to print out each segment or you'll just keep printing the first one over and over again.
When you exit the loop & try to print laenge_drei[0]
again, it will still have the first value. Don't forget to free your memory.
Upvotes: 2