Variadic functions-ascending order - c

Write an ascending function (int n, char type, ...) that receives a number n of values ​​and returns 1 if they are in strictly ascending order, otherwise 0. The type character indicates the type of values ​​and can be 'd' - you, 'in' - double.
Here is my try,but i'm kinda stuck.
double asc(int n,char tip,...)
{
va_list va;
va_start(va,tip);
va_list var;
va_start(va,tip);
while(--n)
{
if(tip=='d')
{
int va1=va_arg(va,int);
if( va>va1)
return 1;
else
return 0;
}
else
if(tip=='f')
{
double va2=va_arg(va,double);
if(va>va2)
return 1;
else
return 0;
}
}
return 0;
}
int main(int argc, char const *argv[])
{
asc(3,'d',-1,7,9);
return 0;
}

int asc(int n,char tip,...)
{
va_list va;
va_start(va,tip);
int result = 1;
union
{
int i;
double d;
}val1, val2;
if (n >= 2)
{
for(int i = 0; i < n-1; i++)
{
switch(tip)
{
case 'i':
if(!i) {val1.i = va_arg(va, int);}
val2.i = va_arg(va, int);
if( val1.i > val2.i)
{result = 0; goto function_return;}
val1.i = val2.i;
break;
case 'd':
if(!i) {val1.d = va_arg(va, double);}
val2.d = va_arg(va, double);
if( val1.d > val2.d)
{result = 0; goto function_return;}
val1.d = val2.d;
break;
default:
break;
}
}
}
function_return:
va_end(va);
return result;
}
int main(int argc, char const *argv[])
{
printf("%d\n", asc(4,'d',-1.0,7.0,9.0,0.0));
return 0;
}

Related

ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

I am trying to run this code on my local machine, but I am receiving the following errors:
ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings] error in my Terminal
File is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher.
These erros are blocking me compiling the code, I am using C | Visual Studio Code | Windows 10 and MSY2 Ming64w to compile my code - can you help me solve this?
my.functions.h
#ifndef HW1
#define HW1
#include <stdio.h>
int str_length(char*);
void str_copy(char* src, char* dest);
int str_find(char* src, char* dest);
int get_unnamed_argument(int index, int argc, char **argv, char *result);
int get_named_argument(int index, int argc, char **argv, char *result);
#endif
my_fuctions.c
#include <stdio.h>
#include "my_functions.h"
int str_length(char* string) {
int c = 0;
for (c = 0; string[c] != '\0'; c++);
return c;
}
void str_copy(char* d, char* source)
{
int i;
for (i = 0; source[i] != '\0'; i++)
{
d[i] = source[i];
}
d[i] = '\0';
}
int str_find(char* needle, char* haystack)
{
int c,x;
for(c = 0; c < str_length(haystack); c++){
if (needle[0] == haystack[c]){
int count = 0;
for(x = 0; x < str_length(needle); x++){
if(needle[x] == haystack[c+x]){
count++;
}
}
if (count == str_length(needle)){
return c;
}
}
}
return -1;
}
int get_unnamed_argument(int index, int argc, char **argv, char *result) {
int c;
for (c = 0;c <= index;c++) {
if (index > argc - 1) {
return -1;
}
else if (str_find("=",argv[c]) != -1) {
index++;
}
else if (str_find("--",argv[c]) != -1) {
return -1;
}
else if (c == index) {
str_copy(result,argv[c]);
return str_length(argv[c]);
}
}
return -1;
}
int get_named_argument(int index, int argc, char **argv, char *result) {
int c;
for (c = 0; c <= index; c++) {
if (index > argc - 1) {
return -1;
}
else if (str_find("=",argv[c]) == -1) {
index++;
}
else if (str_find("--",argv[c]) != -1) {
return -1;
}
else if (c == index) {
str_copy(result, argv[c]);
return str_length(argv[c]);
}
}
return -1;
}
main.c
#include <stdio.h>
#include "my_functions.c"
#include "my_functions.h"
int main(int argc, char **argv) {
char t[1];
int counter;
scanf("%s %i", t, &counter);
if (str_length(t) == 1 && str_find("n", t) != -1)
{
if (counter <= 0)
{
counter = argc;
}
int c;
for (c = 0; c < counter; c++)
{
char result[255];
int arg_len = get_named_argument(c, argc, argv, result);
if (arg_len == -1)
{
return 0;
}
printf("%s\n", result);
}
} else if (str_length(t) == 1 && str_find("u", t) != -1)
{
if (counter <= 0)
{
counter = argc;
}
int c;
for (c = 0; c < counter; c++)
{
char result[255];
int arg_len = get_unnamed_argument(c, argc, argv, result);
if (arg_len == -1)
{
return 0;
}
printf("%s\n", result);
}
} else {
if (counter <= 0)
{
counter = argc;
}
int c;
for (c = 0; c < counter; c++) {
if (str_find("--", argv[c]) != -1)
{
return 0;
}
printf("%s\n", argv[c]);
}
}
return 0;
}

My problem with the size of the number in the My_Mastermind minigame

can you help me with the size of the digits, for example, when I enter 01234, then everything works as it should, but it shouldn’t, the limit of digits should be within four.When I enter some four-digit number, everything works as it should work. But when some five-digit, six-digit or even more, then everything works as if it should be, but it should not work like that. And when I enter numbers that are less than four-digit, for example 123 , then it gives an error and it's good. But when I enter numbers that are more than four digits, it does not give an error and works as if it should be so.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
typedef struct s_mastermind {
int my_attempt;
char* my_code;
} my_mastermind;
my_mastermind* settings_function(my_mastermind* mastermind, int argc, char** argv);
int checking_for_correctness_num(char* _string);
int wrong_input(int progress,char* num_code);
my_mastermind* my_function();
int check_function(char* string);
char* input_function();
int mis_placed_pieces(char* bit, char* num_code);
int well_placed_pieces(char* bit, char* num_code);
int code_checker(char* bit, char* num_code);
char* size_of_function(char* strye);
char* my_strcpy(char* num1, char* num2) {
for(int i = 0; num2[i] != 0; i++) {
num1[i] = num2[i];
}
return num1;
}
int my_strlen(char* num1) {
return (*num1) ? my_strlen(++num1) + 1 : 0;
}
my_mastermind* my_function() {
my_mastermind* num = malloc(sizeof(my_mastermind));
num->my_code = malloc(5);
num->my_code[4] = '\0';
my_strcpy(num->my_code, "");
num->my_attempt = 10;
return num;
}
my_mastermind* settings_function(my_mastermind* mastermind, int argc, char** argv) {
char* bit;
for(int i = 0; i < argc;) {
if (my_strlen(argv[i]) == 2 && argv[i][0] == '-') {
if(argv[i][1] == 'c') {
char* num_code = argv[i + 1];
if(wrong_input(argc,num_code) != 0) {
break;
}
my_strcpy(mastermind->my_code, num_code);
}else if(argv[i][1] == 't') {
if(checking_for_correctness_num(argv[i + 1]) == 0) {
mastermind->my_attempt = check_function(argv[i + 1]);
}
} else {
printf("WRONG FLAG RESTART THE GAME!!!\n");
}
}
i += 1;
}
return mastermind;
}
int wrong_input(int progress,char* num_code) {
// if(my_strlen(num_code) != 4) {
// printf("Code bigger than 4\n");
// }
if(checking_for_correctness_num(num_code) == 1) {
printf("Wrong input!\n> ");
fflush(stdout);
char* code = input_function();
char* variable = size_of_function(code);
free(code);
int results = 1;
if(wrong_input(progress,variable) == 0) {
results = code_checker(num_code, variable);
}
free(variable);
return results;
}
return 0;
}
int checking_for_correctness_num(char* _string) {
for(int i = 0; _string[i] != '\0'; i++) {
if(!(_string[i] >= '0' && _string[i] <= '9')) {
return 1;
}
}
return 0;
}
int check_function(char* string) {
int check_num = 0;
for(int i = 0; string[i] != '\0'; i++) {
check_num = check_num * 10 + (string[i] - '0');
}
return check_num;
}
char* input_function() {
char* getting = malloc(101);
getting[100] = '\0';
read(0, getting, 100);
fflush(stdout);
return getting;
}
int game_progress(int progress, char* bit) {
printf("Round: %d\n> ", progress);
fflush(stdout);
char* code = input_function();
char* variable = size_of_function(code);
free(code);
int results = 1;
if(wrong_input(progress,variable) == 0) {
results = code_checker(bit, variable);
}
free(variable);
return results;
}
void game_action(my_mastermind* mastermind) {
int current_try = 0;
for (;current_try < mastermind->my_attempt;) {
int results = game_progress(current_try, mastermind->my_code);
current_try += 1;
if(results == 0) {
printf("Congratz! You did it!\n");
break;
}
}
}
int code_checker(char* bit, char* num_code) {
int good_w = well_placed_pieces(bit, num_code);
int not_good_m = mis_placed_pieces(bit, num_code);
if(good_w == 3 || good_w == 2 || good_w == 1 || not_good_m == 3 || not_good_m == 2 || not_good_m == 1){
printf("Well placed pieces: %d\nMisplaced pieces: %d\n---\n", good_w,not_good_m);
}
if(good_w == 4) {
return 0;
} else {
return 1;
}
}
int well_placed_pieces(char* bit, char* num_code) {
int number = 0;
for(int i = 0; i < 4; i++) {
if (bit[i] == num_code[i]) {
number += 1;
}
}
return number;
}
int mis_placed_pieces(char* bit, char* num_code) {
int number = 0;
int i = 0;
int j = 0;
while(i < 4) {
i++;
if (bit[i] == num_code[i]) {
number += 1;
}
}
return number;
}
char* size_of_function(char* strye) {
char* new_string = malloc(5);
new_string[4] = '\0';
for(int i = 0; i < 4;i++){
new_string[i] = strye[i];
}
return new_string;
}
int main(int argc, char** argv) {
printf("Will you find the secret code?\n---\n");
my_mastermind* mastermind = my_function();
settings_function(mastermind, argc, argv);
game_action(mastermind);
free(mastermind);
return 0;
}
The problem is that you size_of_function assumes the input string is exactly 4 character long, not counting the '\0'. You should either check if the input string and return a error via a NULL pointer, or fully copy the string and check later.
Returning a NULL pointer require the least modification. You can do it by checking the input string size first :
char* size_of_function(char* strye) {
if(my_strlen(strye) != 4)
return NULL;
char* new_string = malloc(5);
new_string[4] = '\0';
for(int i = 0; i < 4;i++){
new_string[i] = strye[i];
}
if (strye[4] == '\r' || strye[4] == '\n' || strye[4] == '\0')
return new_string;
free(new_string);
return NULL;
}
Then, in wrong_input(), check if num_code is NULL :
int wrong_input(int progress,char* num_code) {
if(num_code == NULL || checking_for_correctness_num(num_code) == 1) {
printf("Wrong input!\n> ");
fflush(stdout);
char* code = input_function();
char* variable = size_of_function(code);
free(code);
int results = 1;
if(wrong_input(progress,variable) == 0) {
results = code_checker(num_code, variable);
}
free(variable);
return results;
}
return 0;
}
It is critical to check if num_code is NULL before calling checking_for_correctness_num(). In C the || operator evaluates the left operand first and skip the second operand evaluation if the first one is true. This way we can ensure that we never pass a NULL pointer to checking_for_correctness_num().
wrong_input() is called recursively and allocates memory without freeing it before calling itself. This can eat up memory fast and is generality considered to be bad practice.
Also, you've implemented my_strlen() as a recursive function, which isn't necessary. Using a loop is better :
int my_strlen(char* num1) {
int index = 0;
while(num1[index++]); //Note that 'index' is post-incremented
return index - 1; //Subtract one to account for the last post increment
}

cant seem to figure out this header file mtrand32.h

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <mtrand32.h>
#define OPERATOR_ADD '+'
#define OPERATOR_SUBTRACT '-'
#define OPERATOR_MULTIPLY '*'
#define OPERATOR_DIVIDE '/'
#define WORD_BITS 32U
#define STREAMS_N 4U
typedef struct
{
unsigned int *words;
unsigned int ones;
}
stream_t;
int random_bit(unsigned int, unsigned int, stream_t *, unsigned int,
unsigned int);
void add_one(stream_t *, unsigned int, unsigned int);
void print_stream(int, stream_t *, unsigned int, int);
void next_bit(unsigned int, unsigned int *, unsigned int *);
int main(void)
{
unsigned int w_bits, a_ones, b_ones, oper, s_ones, stream_words_n,
*words, stream_idx, q, word_idx, weight, bit;
stream_t *streams;
if (scanf("%u", &w_bits) != 1 || w_bits < 1)
{
fprintf(stderr, "Invalid w_bits\n");
fflush(stderr);
return EXIT_FAILURE;
}
if (scanf("%u", &a_ones) != 1 || a_ones > w_bits)
{
fprintf(stderr, "Invalid a_ones\n");
fflush(stderr);
return EXIT_FAILURE;
}
if (scanf("%u", &b_ones) != 1 || b_ones > w_bits)
{
fprintf(stderr, "Invalid b_ones\n");
fflush(stderr);
return EXIT_FAILURE;
}
getchar();
oper = getchar();
switch (oper)
{
case OPERATOR_ADD:
case OPERATOR_SUBTRACT:
case OPERATOR_MULTIPLY:
case OPERATOR_DIVIDE:
break;
default:
fprintf(stderr, "Invalid operator\n");
fflush(stderr);
return EXIT_FAILURE;
}
s_ones = w_bits/2;
stream_words_n = (w_bits-1)/WORD_BITS+1;
words = (unsigned int*)calloc(stream_words_n*STREAMS_N, sizeof(unsigned
int));
if (!words) {
fprintf(stderr, "Could not allocate memory for words\n");
fflush(stderr);
return EXIT_FAILURE;
}
streams = (stream_t*)malloc(sizeof(stream_t)*STREAMS_N);
if (!streams) {
fprintf(stderr, "Could not allocate memory for streams\n");
fflush(stderr);
free(words);
return EXIT_FAILURE;
}
for (stream_idx = 0; stream_idx < STREAMS_N; stream_idx++) {
streams[stream_idx].words = words+stream_words_n*stream_idx;
streams[stream_idx].ones = 0;
}
smtrand32((unsigned int)time(NULL));
q = 0;
word_idx = 0;
weight = 1;
for (bit = 0; bit < w_bits; bit++) {
int bit_a = random_bit(w_bits, a_ones, streams, word_idx, weight),
bit_b = random_bit(w_bits, b_ones, streams+1U, word_idx, weight);
switch (oper) {
int bit_s;
case OPERATOR_ADD:
bit_s = random_bit(w_bits, s_ones, streams+2, word_idx, weight);
if ((bit_a && bit_s) || (bit_b && !bit_s)) {
add_one(streams+3, word_idx, weight);
}
break;
case OPERATOR_SUBTRACT:
bit_s = random_bit(w_bits, s_ones, streams+2, word_idx, weight);
if ((bit_a && bit_s) || (!bit_b && !bit_s)) {
add_one(streams+3, word_idx, weight);
}
break;
case OPERATOR_MULTIPLY:
if (bit_a && bit_b) {
add_one(streams+3, word_idx, weight);
}
break;
case OPERATOR_DIVIDE:
if (bit_a) {
if (bit_b) {
q = !q;
if (q) {
add_one(streams+3, word_idx, weight);
}
}
else {
q = 1;
add_one(streams+3, word_idx, weight);
}
}
else
{
if (bit_b)
{
q = 0;
}
else {
if (q)
{
add_one(streams+3, word_idx, weight);
}
}
}
break;
default:
break;
}
next_bit(bit, &word_idx, &weight);
}
if (oper == OPERATOR_ADD || oper == OPERATOR_SUBTRACT) {
print_stream('a', streams, w_bits, 1);
print_stream('b', streams+1, w_bits, 1);
print_stream('s', streams+2, w_bits, 0);
print_stream('y', streams+3, w_bits, 1);
}
else {
print_stream('a', streams, w_bits, 0);
print_stream('b', streams+1, w_bits, 0);
print_stream('y', streams+3, w_bits, 0);
}
fflush(stdout);
free(streams);
free(words);
return EXIT_SUCCESS;
}
int random_bit(unsigned int w_bits, unsigned int x_ones, stream_t *stream,
unsigned int word_idx, unsigned int weight)
{
if ((unsigned int)(mtrand32()/(UINT32_MAX+1.0)*w_bits) < x_ones)
{
add_one(stream, word_idx, weight);
return 1;
}
return 0;
}
void add_one(stream_t *stream, unsigned int word_idx, unsigned int weight)
{
stream->words[word_idx] += weight;
stream->ones++;
}
void print_stream(int symbol, stream_t *stream, unsigned int w_bits, int
bipolar)
{
unsigned int word_idx, weight, bit;
printf("%c = ", symbol);
word_idx = 0;
weight = 1;
for (bit = 0; bit < w_bits; bit++)
{
if (stream->words[word_idx] & weight)
{
putchar('1');
}
else
{
putchar('0');
}
next_bit(bit, &word_idx, &weight);
}
printf(" (");
if (bipolar)
{
printf("%d", (int32_t)stream->ones*2-(int32_t)w_bits);
}
else
{
printf("%u", stream->ones);
}
printf("/%u)\n", w_bits);
}
void next_bit(unsigned int bit, unsigned int *word, unsigned int *weight)
{
if (bit%WORD_BITS == WORD_BITS-1)
{
*word += 1;
*weight = 1;
}
else
{
*weight *= 2;
}
}
There are the errors that i am facing :
[Error] G:\Stochastic Computing Machine\Stochastic.cpp:5:22:
mtrand32.h: No such file or directory
[Error] G:\Stochastic Computing Machine\Stochastic.cpp:82: error:
`smtrand32' was not declared in this scope
[Error] G:\Stochastic Computing Machine\Stochastic.cpp:158: error:
`mtrand32' was not declared in this scope
[Error] G:\Stochastic Computing Machine\Stochastic.cpp:158: error:
`UINT32_MAX' was not declared in this scope
i searched for mtrand32.h but couldn't find it

Only printing last line of txt file when reading into struct array in C

I am reading from a txt file into an array of structures. Example txt:
-4.5 -1 0 0
4.0 1 0 0
8 0 1 2
12.1 0 -6 1
-3.2 2.5 -3.0 4
The 4 values of each line correspond to the 4 values in the structure. The file may contain up to 100 lines (MAX is defined as 100). With the following code I am trying to store each line into the respective index of the struct array and then print:
FILE *fileName = NULL;
typedef struct chargeData_struct {
double Q, x, y, z;
} ChargeData;
ChargeData values[MAX], *p = values;
fileName = fopen("charge2.txt", "r");
if (fileName == NULL)
{
printf("ERROR: Could not open file.");
}
int k = 0;
while (fscanf(fileName, "%lf %lf %lf %lf", &p[k].Q, &p[k].x, &p[k].y, &p[k].z) != EOF);
{
printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
k++;
}
fclose(fileName);
However, only the last line of the txt file is printed. Is the same index of the struct array being overwritten each time?
You are using an extra semicolon which makes all the trouble, here:
while (fscanf(...) != EOF);
{
...
Remove it and you should be fine.
What happens with your code is that while(..); is equivalent to this:
while(...)
{
; // do nothing
}
thus does not enter the body (the one you think is the body) of your loop (since the actual body does nothing). However scanf() continues to parse the file, and then this section of your code executes:
{
printf("%f %f %f %f\n", p[k].Q, p[k].x, p[k].y, p[k].z);
k++;
}
independently, where the curly braces are treated like they wanted to state scope.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define LINE_BUFFER_LEN (512)
#define RESERVE_NEWLINDE 0
#define AUTO_FILTER_NEWLINDE 1
typedef int (* LINE_READER)(char * pstrLine, int uiBufferLen, void * pvData);
typedef struct st_HW_SSP_CONFIG
{
const char * pstrConfigPath;
LINE_READER pfLineReader;
FILE * pstFile;
void * pvData;
int CurrentLine;
int Flag;
} CONFIG_ST;
int CloseConfig(CONFIG_ST * pstConfig)
{
if (!pstConfig)
{
// record error
return -1;
}
if (fclose(pstConfig->pstFile))
{
// record error
}
return 0;
}
int OpenConfigFile(const char * pstrFilePath, CONFIG_ST * pstConfig)
{
FILE * pstFile = NULL;
if ((!pstrFilePath) || (!pstConfig))
{
return -1;
}
pstFile = fopen(pstrFilePath, "r");
if (!pstFile)
{
return -1;
}
pstConfig->pstFile = pstFile;
pstConfig->pstrConfigPath = pstrFilePath;
pstConfig->Flag = RESERVE_NEWLINDE;
return 0;
}
int IsNullStr(const char *pcStr)
{
const char *pcTmp = pcStr;
while ('\0' != *pcTmp)
{
if (!isspace(*pcTmp))
{
return 0;
}
pcTmp++;
}
return 1;
}
int IsEffectiveLine(char acFileLineBuffer[LINE_BUFFER_LEN])
{
if (0 == strlen(&acFileLineBuffer[0]))
{
return 0;
}
if ('#' == acFileLineBuffer[0]) // strip as a comment line
{
return 0;
}
if (IsNullStr(&acFileLineBuffer[0]))
{
return 0;
}
return 1;
}
void FilterNewLine(char* pcLine, int MaxNumLen)
{
int uiLen = strlen(pcLine);
if (uiLen > 1)
{
if ('\n' == pcLine[uiLen - 1])
{
pcLine[uiLen - 1] = '\0';
if (uiLen > 2)
{
if ('\r' == pcLine[uiLen - 2])
{
pcLine[uiLen - 2] = '\0';
}
}
}
}
return;
}
int ReadConfigFile(CONFIG_ST * pstConfig)
{
char acFileLineBuffer[LINE_BUFFER_LEN] = {0};
char * pstrRead = NULL;
int Ret = 0;
if (!pstConfig)
{
return -1;
}
if ((!pstConfig->pstFile) || (!pstConfig->pfLineReader))
{
return -1;
}
rewind(pstConfig->pstFile);
pstConfig->CurrentLine = 0;
do
{
memset((void *)&acFileLineBuffer[0], 0, LINE_BUFFER_LEN);
pstrRead = fgets(&acFileLineBuffer[0], LINE_BUFFER_LEN - 1, pstConfig->pstFile);
if (pstrRead)
{
pstConfig->CurrentLine ++;
if (0 == IsEffectiveLine(acFileLineBuffer))
{
continue;
}
if (AUTO_FILTER_NEWLINDE == pstConfig->Flag)
{
FilterNewLine(acFileLineBuffer, LINE_BUFFER_LEN - 1);
}
if (pstConfig->pfLineReader)
{
Ret = pstConfig->pfLineReader(&acFileLineBuffer[0],
LINE_BUFFER_LEN,
pstConfig->pvData);
if (Ret)
{
break;
}
}
}
}
while (pstrRead);
return Ret;
}
int ReadConfigFileEx(const char * pFilePath,
LINE_READER pfReader,
void * pData, int Flag)
{
int Ret = 0;
CONFIG_ST stConfig = {0};
Ret = OpenConfigFile(pFilePath, &stConfig);
if (Ret)
{
return Ret;
}
stConfig.pfLineReader = pfReader;
stConfig.pvData = pData;
stConfig.Flag = Flag;
Ret = ReadConfigFile(&stConfig);
CloseConfig(&stConfig);
return Ret;
}
int StringSplit(char *pcStr, char cFlag,
char * pstArray[], int MaxNum,
int *pNum)
{
char * pcStrTemp = 0;
unsigned int uiIndex = 0;
pcStrTemp = pcStr;
while (pcStrTemp)
{
pstArray[uiIndex] = pcStrTemp;
pcStrTemp = strchr(pcStrTemp, cFlag);
if (pcStrTemp)
{
*pcStrTemp = '\0';
pcStrTemp ++;
uiIndex ++;
}
if (uiIndex >= MaxNum)
{
break;
}
}
if (0 != MaxNum)
{
*pNum = uiIndex >= MaxNum ? (MaxNum - 1) : uiIndex;
}
else
{
*pNum = 0;
}
return 0;
}
int MyLineReader(char * pstrLine, int uiBufferLen, void * pvData)
{
printf("Read line:[%s]\r\n", pstrLine);
char *pArray[8] = {0};
int Num = 0;
int index = 0;
StringSplit(pstrLine, ' ', pArray, 8, &Num);
for (index = 0; index <= Num; index ++)
{
printf("Get value :[%s]\r\n", pArray[index]);
}
return 0;
}
int main(int argc, char * argv[])
{
int ret = 0;
if (argc != 2)
{
printf("Please input file to read.\r\n");
return 0;
}
ret = ReadConfigFileEx(argv[1], MyLineReader, NULL, AUTO_FILTER_NEWLINDE);
if (ret)
{
printf("Open file error.\r\n");
}
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++) {

Resources