Skip to content
Snippets Groups Projects
Commit f28421aa authored by Michaël El Kharroubi's avatar Michaël El Kharroubi :satellite:
Browse files

Merge branch 'list_c' into 'main'

Added C code for finding the minimum value in an array

See merge request orestis.malaspin/rust-101!1
parents 96086dc2 2d309f60
No related branches found
No related tags found
No related merge requests found
---
Language: Cpp
# BasedOnStyle: Google
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveMacros: None
AlignConsecutiveAssignments: None
AlignConsecutiveBitFields: None
AlignConsecutiveDeclarations: None
AlignEscapedNewlines: Left
AlignOperands: Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortEnumsOnASingleLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: true
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
QualifierAlignment: Leave
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: true
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
PackConstructorInitializers: NextLine
BasedOnStyle: ''
ConstructorInitializerAllOnOneLineOrOnePerLine: false
AllowAllConstructorInitializersOnNextLine: true
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*\.h>'
Priority: 1
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 3
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '([-_](test|unittest))?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseLabels: true
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentExternBlock: AfterExternBlock
IndentRequires: false
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
LambdaBodyIndentation: Signature
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 4
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 4
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PenaltyIndentedWhitespace: 0
PointerAlignment: Left
PPIndentWidth: -1
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
- ParseTestProto
- ParsePartialTestProto
CanonicalDelimiter: pb
BasedOnStyle: google
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterOverloadedOperator: false
BeforeNonEmptyParentheses: false
SpaceAroundPointerQualifiers: Default
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: Never
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
BitFieldColonSpacing: Both
Standard: Auto
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseCRLF: false
UseTab: Never
WhitespaceSensitiveMacros:
- STRINGIZE
- PP_STRINGIZE
- BOOST_PP_STRINGIZE
- NS_SWIFT_NAME
- CF_SWIFT_NAME
...
.vscode
min_list
*.o
CC=gcc
CFLAGS=-g -std=gnu11 -Wall -Wextra -pedantic -fsanitize=address -fsanitize=leak -fsanitize=undefined
LDFLAGS=-fsanitize=address -fsanitize=leak -fsanitize=undefined
SOURCES=$(wildcard *.c)
OBJECTS=$(SOURCES:.c=.o)
TARGET = min_list
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(CC) $^ -o $@ $(LDFLAGS)
.PHONY = clean
clean:
rm -f $(OBJECTS) $(TARGET)
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INT 100
const char *usage_msg =
"Error wrong number of arguments.\n"
"Usage: ./min_list <num1> <num2> ...\n"
" where <num1>, <num2>, ... must be valid integers.\n";
// Copies the value of the smallest value in the tab array in the min variable.
// Returns the pointer to a newly allocated value of the minimum value of the
// array if everything went fine. Returns NULL otherwise
int *list_find_min(int *tab, int size);
// Prints all the element in the tab array.
// Returns -1 if size <= 0
// Returns -2 if tab is NULL
// Any other value means that everything went fine
int list_print(int *tab, int size);
// Exits if the error code shows invalidity
void error_handling(int error_code, int **tab);
// Parses a string to an integer.
// Returns a pointer to newly allocated data.
// Returns NULL if conversion failed.
int *parse_int(char *arg_to_transform);
// Reads the command line inputs and stores them
// in a newly allocated array.
// Returns the array with the parsed numbers or NULL if allocation failed or an
// invalid number was parsed.
int *read_input(int size, char *char_num[]) {
int *tab = malloc(size * sizeof(*tab));
if (NULL == tab) {
fprintf(stderr, "Memory allocation failed\n");
return NULL;
}
for (int i = 0; i < size; ++i) {
int *num = parse_int(char_num[i]);
if (NULL == num) {
free(tab);
fprintf(stderr, "Tried to parse %s which is not a valid integer.\n",
char_num[i]);
return NULL;
}
tab[i] = *num;
free(num);
}
return tab;
}
int main(int argc, char *argv[]) {
if (argc == 1) {
fprintf(stderr,
"Error wrong number of arguments.\n"
"%s",
usage_msg);
return EXIT_FAILURE;
}
int size = argc - 1;
int *tab = read_input(size, &argv[1]);
if (NULL == tab) {
fprintf(stderr, "Failure during argument parsing.\n");
return EXIT_FAILURE;
}
printf("Among the numbers in the list:\n");
error_handling(list_print(tab, size), &tab);
int *min = list_find_min(tab, size);
if (NULL == min) {
fprintf(stderr, "Could not find the minimum of the array.\n");
free(tab);
tab = NULL;
return EXIT_FAILURE;
}
printf("The value of the minimum of the numbers is: %d\n", *min);
free(min);
free(tab);
tab = NULL;
return EXIT_SUCCESS;
}
// Checks if size is valid and tab is not NULL
int list_is_valid(int *tab, int size) {
if (size <= 0) {
return -1;
}
if (NULL == tab) {
return -2;
}
return 0;
}
int list_print(int *tab, int size) {
int code = list_is_valid(tab, size);
if (code < 0) {
return code;
}
for (int i = 0; i < size; ++i) {
printf("%d ", tab[i]);
}
printf("\n");
return code;
}
int *list_find_min(int *tab, int size) {
int code = list_is_valid(tab, size);
if (code < 0) {
return NULL;
}
int *min = malloc(sizeof(*min));
*min = tab[0];
for (int i = 1; i < size; ++i) {
if (tab[i] < *min) {
*min = tab[i];
}
}
return min;
}
void error_handling(int error_code, int **tab) {
switch (error_code) {
case -1:
fprintf(stderr, "Return value, %d. Size is <= 0.\n", error_code);
free(*tab);
*tab = NULL;
exit(EXIT_FAILURE);
break;
case -2:
fprintf(stderr, "Tab is NULL.\n");
free(*tab);
*tab = NULL;
exit(EXIT_FAILURE);
break;
default:
break;
}
}
int *parse_int(char *arg_to_transform) {
if (strlen(arg_to_transform) == 0) {
return NULL; // empty string to parse
}
char *remaining;
errno = 0; // errno == 0 (defined in errno.h) means everything went fine
long arg = strtol(arg_to_transform, &remaining,
10); // number is parsed in base 10
if (*remaining != '\0' || errno != 0) {
return NULL; // Empty string parsed or an error occurred
}
if (arg < INT_MIN || arg > INT_MAX) {
return NULL; // Not within the limits of an int
}
int *num = malloc(sizeof(*num));
*num = (int)arg;
return num;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment