C program using array char* crash - c

I want to build a program that allow to insert name and print out. But the program crash whenever it begin.
This is my main class:
void main(int argc, char *argv[]) {
int* n = (int*) malloc(sizeof(int));
char listStudent[100][31];
char* name = (char*) malloc(31);
int id;
*n = 0;
addStudent("John ABC", listStudent, n);
addStudent("David Davinci", listStudent, n);
}
And some function to call
void addStudent(char name[31], char listName[][31], int *pn) {
int id;
id = findName(name, listName, *pn);
if(id < 0) {
addName(name, listName, *pn);
printf("%s has been added", name);
} else
printf("The student was exist\n");
}
int findName(char name[31], char listName[][31], int n) {
int found = FALSE;
int i, id;
id = -1;
for(i = 0; i < n && (!found); i++)
if(stricmp(listName[i], name) == 0) {
found = TRUE;
id = i;
}
return id;
}
void addName(char str[31], char listName[][31], int* pn) {
if(*pn > 100)
printf("List is full !!");
else
strcpy(listName[(*pn)++],str);
}
Thanks advance for your help!!

It is not crashing.
Now its up to you to make it work as you wish.
void addStudent(char* name, char listName[][31], int* n) {
int id;
// printf("%s", name);
id = findName(name, listName, n);
if(id < 0) {
addName(name, listName, n);
printf("%s has been added\n", name);
} else
printf("The student already exists\n");
}
int findName(char* name, char listName[][31], int n) {
int found = 0;
int i, id;
id = -1;
for(i = 0; i<100 && &(n) < 100 &&(!found); i++)
if(strcmp(listName[i], name) == 0) {
found = 1;
id = i;
}
return id;
}
void addName(char str[31], char listName[][31], int* pn) {
if(pn > 100)
printf("List is full !!\n");
else
strcpy(listName[(*pn)++],str);
}
void main(int argc, char *argv[]) {
int n = 0;
char listStudent[100][31];
int id;
addStudent("John ABC", listStudent, &(n));
addStudent("David Davinci", listStudent, &(n));
}

Related

How can I split a string into a struct?

I want to get a list of all substring separated by "," and put each into a struct.
e.g if i receive "connor,michel" i want to put "connor" in struct[0].name and "michel" in struct[1].name. for now I have this:
struct crit
{
char* titre;
char* noms;
int annees;
float cote;
};
char * les_noms = (char*) malloc(sizeof(char*));
int i = 0;
char *item = strtok(noms, ",");
while(item != NULL)
{
les_noms[i++] = item;
printf("un nom = %s\n", item);
item = strtok(NULL, ",");
}
sorry for the french words.
edit: maked up my mind about les_nom
What about this?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person
{
char *name;
};
int main()
{
struct person *persons = NULL;
int num_persons = 0;
char names[80] = "joana,cleiton,márcio,elana,joão";
const char sep[2] = ",";
char *item = strtok(names, sep);
while (item != NULL)
{
persons = realloc(persons, ++num_persons * sizeof(struct person));
persons[num_persons - 1].name = malloc(strlen(item)) + 1;
strcpy(persons[num_persons - 1].name, item);
item = strtok(NULL, ",");
}
for (unsigned int i = 0; i < num_persons; i++)
{
printf("%d: %s\n", i, persons[i].name);
}
for (unsigned int i = 0; i < num_persons; i++)
{
free(persons[i].name);
}
free(persons);
}
Or the fixed size solution:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person
{
char *name;
};
int main()
{
char names[80] = "joana,cleiton,márcio,elana,joão";
const char sep[2] = ",";
unsigned int num_persons = 1;
for (unsigned int i = 0; i < strlen(names); i++)
{
if (names[i] == ',')
{
num_persons++;
}
}
struct person persons[num_persons];
char *item = strtok(names, sep);
for (unsigned int i = 0; item != NULL; i++)
{
persons[i].name = malloc(strlen(item) + 1);
strcpy(persons[i].name, item);
item = strtok(NULL, ",");
}
for (unsigned int i = 0; i < num_persons; i++)
{
printf("%d: %s\n", i, persons[i].name);
}
for (unsigned int i = 0; i < num_persons; i++)
{
free(persons[i].name);
}
}
You probally will need more items in the struct, it is easy, look:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person
{
char *name;
int len_name;
int id;
};
int main()
{
char names[80] = "joana,cleiton,márcio,elana,joão";
const char sep[2] = ",";
unsigned int num_persons = 1;
for (unsigned int i = 0; i < strlen(names); i++)
{
if (names[i] == ',')
{
num_persons++;
}
}
struct person persons[num_persons];
char *item = strtok(names, sep);
for (unsigned int i = 0; item != NULL; i++)
{
persons[i].name = malloc(strlen(item) + 1);
persons[i].len_name = strlen(item);
persons[i].id = i;
strcpy(persons[i].name, item);
item = strtok(NULL, ",");
}
for (unsigned int i = 0; i < num_persons; i++)
{
printf("%d: %s | %d\n", persons[i].id, persons[i].name, persons[i].len_name);
}
for (unsigned int i = 0; i < num_persons; i++)
{
free(persons[i].name);
}
}

Why is does the file become NULL?

I'm new on the subject of data structures so forgive me if Im asking a stupid question, I've been trying to figure this out myself but got nowhere.
These are the functions I'm working on and I think I initialized the file properly. However I couldn't understand why the function GetString prints an infinite loop of spaces. I have another function that exported some data on the said file. When i deleted the ImportListOfCompanyData function everything seems in order and the file is exported as it should be. However when ImportListOfCompanyData is there, the file is NULL.
void char * GetString(FILE *fp)
{
char c;
while(c != '\n')
{
c = fgetc(fp);
printf("%c", c);
}
}
void ImportListOfCompanyData(char *FileName, struct CompanyType s[], int maxit1, int maxit2)
{
FILE * fp;
char c;
fp = fopen(FileName, "r");
if (fp==NULL)
{
printf("Error creating the file \n");
exit(1);
}
GetString(fp);
fclose(fp);
}
Someone asked for the complete code: It's bit long sorry!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXNUM 100
struct Department
{
char DepName[MAXNUM];
int NuEmp;
double Budget;
int dflag;
};
typedef struct Department DEP;
struct CompanyType
{
char CompName[MAXNUM];
char OwnerName[MAXNUM];
int Year;
double StockPrice;
int flag;
DEP Dep[MAXNUM];
};
struct ImpDepartment
{
char IDepName[MAXNUM];
int INuEmp;
double IBudget;
int Idflag;
};
typedef struct ImpDepartment IDEP;
struct ImpCompanyType
{
char ICompName[MAXNUM];
char IOwnerName[MAXNUM];
int IYear;
double IStockPrice;
int Iflag;
IDEP IDep[MAXNUM];
};
void CreateCompany(struct CompanyType s[], char * cname, char * cowner, int year, double sprice, int i)
{
strcpy(s[i].CompName, cname);
strcpy(s[i].OwnerName, cowner);
s[i].Year = year;
s[i].StockPrice = sprice;
s[i].flag = 0;
}
int PrintCompany(struct CompanyType s[], int maxit1, int maxit2)
{
int flag = 0, i = 0;
while(i <= maxit1)
{
if(s[i].flag == 1)
{
flag = 1;
break;
}
printf("%d. Company %s: \n\n", i + 1, s[i].CompName);
printf("****************\n");
printf("Owned by: %s\n", s[i].OwnerName);
printf("Establishment year: %d\n", s[i].Year);
printf("Stock price: %.2lf\n", s[i].StockPrice);
printf("****************\n\n");
int j = 0;
while(j < maxit2)
{
if(s[i].Dep[j].dflag == 1)
{
flag = 1;
break;
}
printf("****************\n");
printf("%d. Department %s: \n", j + 1, s[i].Dep[j].DepName);
printf("Number of employees: %d\n", s[i].Dep[j].NuEmp);
printf("Budget: %.2lf\n", s[i].Dep[j].Budget);
printf("****************\n\n");
j++;
}
i++;
}
if(flag == 1)
return -1;
else
return 0;
}
int CompareName(char * str1, char * str2)
{
char *stra, *strb;
int result;
result = strcmp(str2, str1);
return result;
}
void DeleteCompany(struct CompanyType s[], char * cname, int n)
{
int i = 0, check = 0;
while(i <= n)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
s[i].flag = 1;
printf("Company %s was successfully deleted!\n", s[i].CompName);
}
else
printf("The input is wrong!");
}
void UnDeleteCompany(struct CompanyType s[], char * cname, int n)
{
int i = 0, check = 0;
while(i <= n)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
if(s[i].flag == 0)
{
printf("The Company %s wasn't deleted in the first place.\n\n", s[i].CompName);
}
else
{
s[i].flag = 0;
printf("Company %s was successfully undeleted!\n\n", s[i].CompName);
}
}
else
printf("The input is wrong!");
}
int SearchForCompany(struct CompanyType s[], char * cname, int maxit, int a)
{
int i = 0;
int check = 0;
int m = 0;
while(i <= maxit)
{
if(CompareName(s[i].CompName, cname)== 0)
{
check = 1;
break;
}
i++;
}
if(check == 1)
{
if(s[i].flag == 1)
{
printf("The company ""%s"" doesn't exist\n\n", cname);
}
else
{
if(a == 1)
{
printf("The company %s was found!", s[i].CompName, s[i].CompName);
m = 1;
}
else
m = 1;
}
}
else
printf("The company ""%s"" doesn't exist\n\n", cname);
if (m == 1)
return i;
else
return -1;
}
void AddDeparments(struct CompanyType s[], char * cname, int maxit, int a, char * dname, int nem, double bud, int depno)
{
int n;
n = SearchForCompany(s,cname, maxit, a);
if(maxit == -1)
return -1;
strcpy(s[n].Dep[depno].DepName, dname);
s[n].Dep[depno].NuEmp = nem;
s[n].Dep[depno].Budget = bud;
s[n].Dep[depno].dflag = 0;
printf("The department %s was created in the %s company\n",s[n].Dep[depno].DepName, s[n].CompName);
}
int SearchForDepartments(struct CompanyType s[], char * dname, int maxit1, int maxit2, int a, int *succ, int *i, int*j)
{
int check = 0;
while((*j) <= maxit1)
{
while((*i) <= maxit2)
{
if(CompareName(s[(*i)].Dep[(*j)].DepName, dname)== 0)
{
check = 1;
break;
}
(*i)++;
}
if(check == 1)
break;
(*j)++;
}
if(check == 1)
{
if(s[(*i)].Dep[(*j)].dflag == 1)
{
printf("The department ""%s"" doesn't exist.\n\n", dname);
}
else
(*succ) = 1;
}
else
printf("The department ""%s"" doesn't exist\n\n", dname);
if ((*succ) == 1)
return 0;
else
return -1;
}
int SearchForDelDepartments(struct CompanyType s[], char * dname, int maxit1, int maxit2, int a, int *succ, int *i, int*j)
{
int check = 0;
while((*j) <= maxit1)
{
while((*i) <= maxit2)
{
if(CompareName(s[(*i)].Dep[(*j)].DepName, dname)== 0)
{
check = 1;
break;
}
(*i)++;
}
if(check == 1)
break;
(*j)++;
}
if(check == 1)
{
if(s[(*i)].Dep[(*j)].dflag == 1)
{
(*succ) = 1;
}
}
else
printf("The department ""%s"" doesn't exist\n\n", dname);
if ((*succ) == 1)
return 0;
else
return -1;
}
void DeleteDepartments(struct CompanyType s[], int maxit1, int maxit2, int a, char * dname)
{
int n, i = 0, j = 0;
int succ = 0;
n = SearchForDepartments(s, dname, maxit1, maxit2, a, &succ, &i, &j);
if(n == -1)
return -1;
if(succ == 1)
{
s[i].Dep[j].dflag = 1;
printf("The department %s was deleted from the %s company\n", dname, s[i].CompName);
}
}
void UnDeleteDepartments(struct CompanyType s[], int maxit1, int maxit2, int a, char * dname)
{
int n, i = 0, j = 0;
int succ = 0;
n = SearchForDelDepartments(s, dname, maxit1, maxit2, a, &succ, &i, &j);
if(n == -1)
return -1;
if(succ == 1)
s[i].Dep[j].dflag = 0;
if(s[i].Dep[j].dflag == 0)
printf("The department %s was undeleted\n", dname);
}
ExportListOfCompanyData(struct CompanyType s[], int maxit1, int maxit2, char * FileName)
{
FILE *fp;
fp = fopen(FileName, "w");
if (fp==NULL)
{
printf("Error creating the file \n");
return -1;
}
int flag = 0, i = 0;
while(i <= maxit1)
{
if(s[i].flag == 1)
{
flag = 1;
break;
}
fprintf(fp,"%s\n", s[i].CompName);
fprintf(fp,"%s\n", s[i].OwnerName);
fprintf(fp,"%d\n", s[i].Year);
fprintf(fp,"%.2lf\n\n", s[i].StockPrice);
int j = 0;
while(j < maxit2)
{
if(s[i].Dep[j].dflag == 1)
{
flag = 1;
break;
}
fprintf(fp,"%s\n", s[i].Dep[j].DepName);
fprintf(fp,"%d\n", s[i].Dep[j].NuEmp);
fprintf(fp,"%.2lf\n\n", s[i].Dep[j].Budget);
j++;
}
i++;
}
if(flag == 1)
return -1;
else
return 0;
fclose(fp);
}
char * GetString(FILE *fp)
{
char * str; char c;
str = (char *)malloc(sizeof(char)* MAXNUM);
while(c != '\n')
{
c = fgetc(fp);
printf("%c", c);
}
}
ImportListOfCompanyData(char *FileName, struct CompanyType s[], int maxit1, int maxit2)
{
FILE * fp;
char c, *str;
str = (char *)malloc(sizeof(char)* MAXNUM);
fp = fopen(FileName, "r");
if (fp==NULL)
{
printf("Error creating the file \n");
exit(1);
}
int i = 0, j = 0, n;
GetString(fp);
fclose(fp);
return 0;
}
int main()
{
struct CompanyType CompanyList[MAXNUM];
CreateCompany(CompanyList, "alara inc", "alara", 2020, 6969, 0);
CreateCompany(CompanyList, "Shah inc", "shah", 2020, 3245, 1);
DeleteCompany(CompanyList, "Shah inc", 1);
SearchForCompany(CompanyList, "Shah inc", 1, 1);
UnDeleteCompany(CompanyList, "Shah inc", 1);
SearchForCompany(CompanyList, "Shah inc", 1, 1);
SearchForCompany(CompanyList, "alara inc", 1, 1);
AddDeparments(CompanyList, "alara inc", 1, 0, "computer", 20, 300, 0);
AddDeparments(CompanyList, "Shah inc", 1, 0, "chemistry", 30, 450, 0);
DeleteDepartments(CompanyList, 0, 1, 0, "chemistry");
UnDeleteDepartments(CompanyList, 0, 1, 0, "computer");
PrintCompany(CompanyList, 1, 1);
UnDeleteDepartments(CompanyList, 0, 1, 0, "chemistry");
ExportListOfCompanyData(CompanyList, 1, 1, "Data.txt");
ImportListOfCompanyData("Data.txt", CompanyList, 1, 1);
PrintCompany(CompanyList, 1, 1);
return 0;
}```
It was a really easy solution. I replaced "w" and "r" with "a+"
I guess it was a stupid question, still learning!

reads txt from file, cut them into words, and display

#pragma warning(disable:4996)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
static WORDS heap[10000];
int heapSize;
void InitHeap()
{
heapSize = 0;
heap[0].words = NULL;
heap[0].count = -1;
}
void InsertHeap(char* string)
{
heapSize++;
strcpy(heap[heapSize].words, string);
int now = heapSize;
while (heap[now / 2].words > string)
{
heap[now] = heap[now / 2];
now /= 2;
}
strcpy(heap[now].words, string);
}
int DeleteHeap()
{
char* minElement, lastElement;
int child, now;
strcpy(minElement, heap[1].words);
strcpy(lastElement, heap[heapSize--].words);
for (now = 1; now * 2 <= heapSize; now = child)
{
child = now * 2;
if (child != heapSize && heap[child + 1].words < heap[child].words)
{
child++;
}
if (lastElement > heap[child].words)
{
strcpy(heap[now].words, heap[child].words);
}
else
{
break;
}
}
strcpy(heap[now].words, lastElement);
return now;
}
typedef struct _WORDS {
char words[64];
int count;
}WORDS;
char* MakeToken(void)
{
int i, j;
static char delim[256];
memset(delim, 0x0, 256);
for (i = 1, j = 0; i < 256; i++)
{
if (!isalpha(i)) delim[j++] = i;
}
return delim;
}
int main() {
int i = 0, cur = 0;
FILE *pFile;
char readLine[1024], *ptr;
char *token = MakeToken();
InitHeap();
pFile = fopen("C:\\Users\\Home\\Desktop\\dataset.txt", "r");
if (pFile == NULL) {
printf("File open failed.\n");
return 0;
}
while (fgets(readLine, 1024, pFile) != NULL) {
ptr = strtok(readLine, token);
while (ptr != NULL) {
InsertHeap(ptr);
ptr = strtok(NULL, token);
}
}
for (i = 0; i < heapSize; i++)
{
cur = DeleteHeap();
printf("%s %d\n", heap[cur].words, heap[cur].count);
}
return 0;
}
Error Message : Run-Time error #3
I want to make program that reads txt from file, cut them into words, and display on console. I make it, but it doesnt work. how to fix it?
I think static WORDS heap<- this part
or
delete part is error.
or its path is failure.
I see following errors in your code:
heap[0].words = NULL;
words is an array, not a dynamyc allocated pointer, so you cannot assign to NULL (you get a compiler error! Seems to me that the WORDS.word variable declaration is uncorrect).
strcpy(minElement, heap[1].words);
strcpy(lastElement, heap[heapSize--].words);
minElement and lastElement are not initialized and not allocated, so the strcpy function will fail.
Here is a way to correct the code, I changed the minimum possible. The following collect the words, count the number of occurences and print the result in alphabetical order:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct _WORDS {
char words[64];
int count;
} WORDS;
static WORDS heap[10000];
int heapSize;
void InitHeap()
{
heapSize = 0;
}
void InsertHeap(char* string)
{
int num = 0;
// Search string in heap array. if found, increase count.
for(num = 0; num < heapSize; ++num)
{
if(strcmp(string, heap[num].words) == 0)
{
heap[num].count++;
return;
}
}
// If not found, add it to the array.
strcpy(heap[heapSize].words, string);
heap[heapSize].count = 1;
heapSize++;
}
char* MakeToken(void)
{
int i, j;
static char delim[256];
memset(delim, 0x0, 256);
for (i = 1, j = 0; i < 256; i++)
{
if (!isalpha(i)) delim[j++] = i;
}
return delim;
}
int compare(const void* v1, const void* v2)
{
return strcmp((const char*)v1, (const char*)v2);
}
int main()
{
int i = 0, cur = 0;
FILE *pFile;
char readLine[1024], *ptr;
char *token = MakeToken();
InitHeap();
pFile = fopen("C:\\Users\\Home\\Desktop\\dataset.txt", "r");
if(pFile == NULL)
{
printf("File open failed.\n");
return 0;
}
while (fgets(readLine, 1024, pFile) != NULL)
{
ptr = strtok(readLine, token);
while (ptr != NULL)
{
InsertHeap(ptr);
ptr = strtok(NULL, token);
}
}
// Order alphabetically the heap array.
qsort(heap, heapSize, sizeof(WORDS), compare);
for (i = 0; i < heapSize; i++)
{
printf("%s %d\n", heap[i].words, heap[i].count);
}
return 0;
}
I've fixed some errors in the code and it started to produce some results. Since I do not understand completely your task, I cannot progress further. The working code is as follows:
#pragma warning(disable:4996)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct _WORDS { char words[64]; int count; }WORDS;
static WORDS app_heap[10000];
int heapSize;
void InitHeap()
{
heapSize = 0;
app_heap[0].words[0] = '\0';
app_heap[0].count = -1;
}
void InsertHeap(char* string)
{
heapSize++;
strcpy(app_heap[heapSize].words, string);
int now = heapSize;
while (app_heap[now / 2].words > string)
{
app_heap[now] = app_heap[now / 2];
now /= 2;
}
strcpy(app_heap[now].words, string);
}
int DeleteHeap()
{
char minElement[64], lastElement[64];
int child, now;
if(heapSize <= 0)
{
printf("Wrong call\n");
return 0;
}
strcpy(minElement, app_heap[1].words);
strcpy(lastElement, app_heap[heapSize--].words);
for (now = 1; now * 2 <= heapSize; now = child)
{
child = now * 2;
if (child != heapSize && app_heap[child + 1].words < app_heap[child].words)
{
child++;
}
if (lastElement > app_heap[child].words)
{
strcpy(app_heap[now].words, app_heap[child].words);
}
else
{
break;
}
}
strcpy(app_heap[now].words, lastElement);
return now;
}
char* MakeToken(void)
{
int i, j;
static char delim[256];
memset(delim, 0x0, 256);
for (i = 1, j = 0; i < 256; i++)
{
if (!isalpha(i)) delim[j++] = i;
}
return delim;
}
int main() {
int i = 0, cur = 0;
FILE *pFile;
char readLine[1024], *ptr;
char *token = MakeToken();
InitHeap();
pFile = fopen("dataset.txt", "r");
if (pFile == NULL) {
printf("File open failed.\n");
return 0;
}
while (fgets(readLine, 1024, pFile) != NULL) {
ptr = strtok(readLine, token);
while (ptr != NULL) {
InsertHeap(ptr);
ptr = strtok(NULL, token);
}
}
for (i = 0; i < heapSize; i++)
{
cur = DeleteHeap();
printf("%s %d\n", app_heap[cur].words, app_heap[cur].count);
}
return 0;
}

Can't free memory from 2D dynamical array

I am having problem with freeing my memory. I did this many times, and it was working fine. Now, it just stops working (no error, anything, just freeze).
How my code looks like:
void args(int argc, char** argv, int *n, int *m, int **matrix, char name[20])
{
int firstIter = TRUE;
int x;
char op;
int** second;
second = NULL;
op = argv[1][0];
for (x = 2; x < argc; x++)
{
if (!firstIter)
{
setName(name, argv[x]);
loadMatrix(*m, *n, second, *name);
opMatrix(*m, *n, matrix, second, &*matrix, op);
}
else
{
setName(name, argv[x]);
loadSizeMatrix(n, m, name);
matrix = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
matrix[i] = (int *)malloc(*m * sizeof(int));
}
second = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
second[i] = (int *)malloc(*m * sizeof(int));
}
loadMatrix(*m, *n, matrix, *name);
firstIter = FALSE;
}
}
printMatrix(*m, *n, matrix);
for (int i = 0; i < *n; i++) {
free(second[i]);
}
free(second[0]); //doesnt work too, and yes, there are data
free(second);
}
second is being filled like this (loadMatrix):
for (int c = 0; c < radky; c++) {
for (int d = 0; d < sloupce; d++) {
fscanf(fp, "%i", &second[c][d]);
// printf("%i", matice[c][d]); // dump
}
}
How can I solve this error?
my full code
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <ctype.h> //tolower
#include <string.h>
#define TRUE 1
#define FALSE !TRUE
/* konstanty */
const enum {
MAX_DELKA_SOUBORU = 10000,
MAX_SOUBOR = 20
};
const enum {
SOUBOR_NENALEZEN = 1,
SPATNE_ARGUMENTY = 2,
LIMIT_NAZEV_SOUBOR = 3,
SPATNY_OP = 4
};
void error(int type);
void zpracovaniArgumentu(int argc, char** argv, char(*nazevSouboru)[MAX_SOUBOR], char(*nazevVystupni)[MAX_SOUBOR], int *n, int *m, int **matice);
void setNazevSouboru(char(*nazev)[MAX_SOUBOR], char *argument);
void vypisMatice(int radky, int sloupce, int **matice);
int nacteniMaticeZeSouboru(int radky, int sloupce, int **matice, char nazev[MAX_SOUBOR]);
int nacteniVelikostiMatice(int *n, int *m, char nazev[MAX_SOUBOR]);
int operaceMatic(int radky, int sloupce, int **prvni, int **druha, int **vysledek, char op);
int main(int argc, char** argv)
{
int n, m; // n = sloupce, m = radky pro prvni matici
int** first;
char nazevSouboru[MAX_SOUBOR], nazevVystupni[MAX_SOUBOR];
char op;
first = NULL;
zpracovaniArgumentu(argc, argv, &nazevSouboru, &nazevVystupni, &n, &m, &*first);
/* for (int i = 0; i < m; i++) {
free(first[i]);
} */
free(first);
system("pause");
return 0;
}
void error(int type)
{
switch (type)
{
case SOUBOR_NENALEZEN: printf("Soubor nenalezen!");
break;
case SPATNE_ARGUMENTY: printf("Program spustte s argumenty [nazev souboru] *[nazev vystupniho souboru]*.\n");
break;
case MAX_DELKA_SOUBORU: printf("Prekrocen maximalni limit delky nazvu souboru (%i).\n", MAX_SOUBOR);
break;
case SPATNY_OP: printf("Program spustte s argumenty [nazev souboru] *[nazev vystupniho souboru]*.\n");
break;
default: printf("Nastala chyba!");
break;
}
system("pause");
exit(type);
}
void zpracovaniArgumentu(int argc, char** argv, char(*nazevSouboru)[MAX_SOUBOR], char(*nazevVystupni)[MAX_SOUBOR], int *n, int *m, int **matice)
{
int firstIter = TRUE;
int doSouboru = FALSE;
int x;
char op;
int** second;
second = NULL;
op = argv[1][0];
for (x = 2; x < argc; x++)
{
if (!firstIter)
{
setNazevSouboru(nazevSouboru, argv[x]);
nacteniMaticeZeSouboru(*m, *n, &*second, *nazevSouboru);
operaceMatic(*m, *n, matice, &*second, &*matice, op);
}
else if (argv[x][0] == '-')
{
switch (argv[x][1])
{
case 'n': doSouboru = TRUE;
break;
default: error(SPATNE_ARGUMENTY);
break;
}
}
else if (doSouboru)
{
setNazevSouboru(nazevVystupni, argv[x]);
}
else
{
setNazevSouboru(nazevSouboru, argv[x]);
nacteniVelikostiMatice(n, m, *nazevSouboru);
matice = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
matice[i] = (int *)malloc(*m * sizeof(int));
}
second = (int **)malloc(*n * sizeof(int*));
for (int i = 0; i < *n; i++) {
second[i] = (int *)malloc(*m * sizeof(int));
}
nacteniMaticeZeSouboru(*m, *n, &*matice, *nazevSouboru);
firstIter = FALSE;
}
}
vypisMatice(*m, *n, matice);
for (int i = 0; i < *n; i++) {
printf("%i",second[i]);
free(second[i]);
}
free(second);
}
void setNazevSouboru(char(*nazev)[MAX_SOUBOR], char *argument)
{
strcpy(*nazev, argument);
strcat(*nazev, ".txt"); //nazev souboru
}
int nacteniVelikostiMatice(int *n, int *m, char nazev[MAX_SOUBOR])
{
FILE *fp = fopen(nazev, "r"); // načtení souboru
int c;
int radky = 1;
int sloupce = 0;
if (!fp)
{
error(SOUBOR_NENALEZEN);
exit(2);
}
else
{
while ((c = fgetc(fp)) != EOF)
{
//tolower(c);
if (c == '\n')
{
radky++;
}
else if ((isdigit(c)) && (radky == 1))
{
sloupce++;
}
}
}
fclose(fp);
*n = sloupce;
*m = radky;
return 0;
}
int nacteniMaticeZeSouboru(int radky, int sloupce, int **matice, char nazev[MAX_SOUBOR])
{
int x;
FILE *fp = fopen(nazev, "r"); // načtení souboru
if (!fp)
{
error(SOUBOR_NENALEZEN);
exit(2);
}
else
{
for (int c = 0; c < radky; c++) {
for (int d = 0; d < sloupce; d++) {
fscanf(fp, "%i", &matice[c][d]);
// printf("%i", matice[c][d]); // dump
}
}
}
fclose(fp);
return 0;
}
int operaceMatic(int radky, int sloupce, int **prvni, int **druha, int **vysledek, char op)
{
int vysledekClip[10][10];
for (int c = 0; c < radky; c++) {
for (int d = 0; d < sloupce; d++) {
switch (op) {
case '+': vysledekClip[c][d] = prvni[c][d] + druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '-': vysledekClip[c][d] = prvni[c][d] - druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '/': vysledekClip[c][d] = prvni[c][d] / druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '%': vysledekClip[c][d] = prvni[c][d] % druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
case '*': vysledekClip[c][d] = prvni[c][d] * druha[c][d];
vysledek[c][d] = vysledekClip[c][d];
break;
default: error(SPATNY_OP);
break;
}
vysledek[c][d] = vysledekClip[c][d];
}
}
return 0;
}
void vypisMatice(int radky, int sloupce, int **matice)
{
int c;
int d;
for (c = 0; c < radky; c++) {
for (d = 0; d < sloupce; d++) {
printf("%i\t", matice[c][d]);
} printf("\n");
}
}
void vypisMaticeDoSouboru(int radky, int sloupce, int **matice, char nazevSouboru[MAX_DELKA_SOUBORU])
{
int c;
int d;
for (c = 0; c < radky; c++) {
for (d = 0; d < sloupce; d++) {
printf("%i\t", matice[c][d]);
} printf("\n");
}
}
You have a problem with the 'second' array. You allocate an array of *n pointers to int but fill *m elements in that array:
second = (int **) malloc(*n * sizeof(int*));<p>
for (int i = 0; i < *m; i++) {

Unreachable Node in Dijkstra's Algorithm

So I'm having trouble with Dijkstra's algorithm (src to dest). I looked at other answers and could not find the solution to my problem. I have used an adjacency list, thus I have a list for vertices, and each vertex has it's own edge list. My problem arises when I have a node that is unreachable. Specifically, it never gets visited thus I'm stuck in my allNotComp while loop. Can anyone help me with a solution? Code is below.
#include <stdlib.h>
#include <stdio.h>
int INFINITY = 9999;
struct edge
{
int vertexIndex;
int vertexWeight;
struct edge *edgePtr;
} edge;
struct vertex
{
int vertexKey;
struct edge *edgePtr;
struct vertex *vertexPtr;
}vertex;
struct vertex *Start = NULL;
void insertEdge(int vertex, int vertex2, int vertexWeight);
void insertVertex(int vertexKey);
int allNotComp(int comp[], int size);
void printPath(int prev[], int src, int dest, int size);
void dijkstra(int src, int size, int dest);
int cost(int curr, int i);
int main(int argc, char * argv[]) {
int k = 1;
int numVertices = atoi(argv[2]);
char* source = argv[3];
char* destination = argv[4];
int src = atoi(argv[3]);
int dest = atoi(argv[4]);
Start = &vertex;
Start->vertexKey = 0;
Start->vertexPtr = NULL;
Start->edgePtr = NULL;
int m = 0;
int flag = 0;
int flag2 = 0;
for(m = 0; m < numVertices; m++){
if(src == m) {
flag = 1;
}
if(dest == m) {
flag2 = 1;
}
}
if(!(flag && flag2)) {
printf("%s ", "ERROR: Src and/or Dest not valid.\n");
exit(0);
}
while(k < numVertices) {
insertVertex(k);
k++;
}
FILE *f = fopen(argv[1], "r");
int numbers[numVertices][numVertices];
char ch;
int i = 0;
int j = 0;
for(m = 0; m < numVertices*numVertices; m++) {
fscanf(f, "%d", &(numbers[i][j]));
j=j+1;
if(j == numVertices) {
i=i+1;
j=0;
}
}
for(i=0;i<numVertices;i++) {
for(j=0;j<numVertices;j++) {
if(i == j && numbers[i][j] != 0) {
printf("%s", "ERROR: All diagonals must be zero.\n");
exit(0);
}
if(i != j) {
insertEdge(i, j, numbers[i][j]);
}
}
}
dijkstra(src, numVertices, dest);
}
void insertEdge(int vertex, int vertex2, int vertexWeight)
{
if(vertexWeight == -1) return;
struct vertex *traverse;
if(vertex == Start->vertexKey) {
traverse = Start;
}
else {
while(traverse->vertexKey != vertex) {
traverse = traverse->vertexPtr;
}
}
struct edge *e,*e1,*e2;
e=traverse->edgePtr;
while(e&& e->edgePtr)
{
e=e->edgePtr;
}
e1=(struct edge *)malloc(sizeof(*e1));
e1->vertexIndex=vertex2;
e1->vertexWeight = vertexWeight;
e1->edgePtr=NULL;
if(e)
e->edgePtr=e1;
else
traverse->edgePtr=e1;
}
void insertVertex(int vertexKey) {
struct vertex *v, *v1, *v2;
v = Start->vertexPtr;
while(v && v->vertexPtr) {
v=v->vertexPtr;
}
v1=(struct vertex *)malloc(sizeof(*v1));
v1->vertexKey = vertexKey;
v1->vertexPtr = NULL;
v1->edgePtr = NULL;
if(v) {
v->vertexPtr = v1;
}
else {
Start->vertexPtr = v1;
}
}
void dijkstra(int src, int size, int dest) {
int comp[size];
int dist[size];
int prev[size];
int i;
for(i = 0; i<size; i++) {
comp[i] = 0;
dist[i] = INFINITY;
prev[i] = -1;
}
comp[src] = 1;
dist[src] = 0;
prev[src] = src;
int curr = src;
int k;
int minDist;
int newDist;
while(allNotComp(comp, size)) {
minDist = INFINITY;
for(i = 0; i<size;i++) {
if(comp[i] == 0) {
newDist = dist[curr] + cost(curr, i);
if(newDist < dist[i]) {
dist[i] = newDist;
prev[i] = curr; }
if(dist[i] < minDist) {
minDist = dist[i];
k=i; }
}
}
curr = k;
comp[curr] = 1;
}
if(dist[dest] < INFINITY) {
printPath(prev, src, dest, size);
printf(":%d\n", dist[dest]);
} else {
printf("%s\n", "NO PATH EXISTS BETWEEN THE TWO VERTICES!");
}
}
int allNotComp(int comp[], int size) {
int i;
for(i = 0; i < size; i++) {
if(comp[i] == 0) {
return 1;
}
}
return 0;
}
int cost(int curr, int i) {
struct vertex *travel;
struct edge *traverse;
travel = Start;
while(travel->vertexPtr != NULL) {
if(travel->vertexKey != curr) {
travel = travel->vertexPtr;
}
else{
break;
}
}
traverse = travel->edgePtr;
while(traverse->edgePtr != NULL) {
if(traverse->vertexIndex != i) {
traverse = traverse->edgePtr;
}
else{
break;
}
}
if(traverse->vertexIndex != i) {
return INFINITY;
}
return traverse->vertexWeight;
}
void printPath(int prev[], int src, int dest, int size) {
if(src == dest) {
printf("%d", src);
}
else {
printPath(prev, src, prev[dest], size);
printf("-%d", dest);
}
}
Although an unreachable node never gets visited, this situation can be detected. If the dists of all unvisited nodes are INFINITY, this means all remaining nodes are unreachable, and you should end the loop.

Resources