a global variable cannot be assigned twice - c

I have faced some problem when doing TDD.
I designed this function:
String *subString;
String *getWordAndUpdate(String *line, char *delimiter) {
String *word = malloc(sizeof(String));
int i;
stringLeftTrim(line);
word->length = 0;
word->startIndex = 0;
for(i = line->startIndex; i < line->length; i++) {
if(line->rawString[i] != ' ') {
word->rawString[i] = line->rawString[i];
line->startIndex++;
word->length++;
} else {
break;
}
}
line->length = line->length - i;
return word;
}
With my String struct:
typedef struct {
char *rawString;
int startIndex;
int length;
} String;
When I call this getWordAndUpdate function the first time it works fine, but when i call second time it says bad memory access.
extern String *subString;
void test_getWordAndUpdate_should_get_the_first_word_from_a_line_of_instruction() {
String oneLineString = {"movwf 0x10", 0, 10};
subString = getWordAndUpdate(&oneLineString, " ,;"); // works fine
TEST_ASSERT_EQUAL('m', subString->rawString[0]);
TEST_ASSERT_EQUAL('o', subString->rawString[1]);
TEST_ASSERT_EQUAL('v', subString->rawString[2]);
TEST_ASSERT_EQUAL('w', subString->rawString[3]);
TEST_ASSERT_EQUAL('f', subString->rawString[4]);
TEST_ASSERT_NOT_EQUAL(' ', subString->rawString[5]);
TEST_ASSERT_NOT_EQUAL('0', subString->rawString[6]);
TEST_ASSERT_NOT_EQUAL('x', subString->rawString[7]);
TEST_ASSERT_NOT_EQUAL('1', subString->rawString[8]);
TEST_ASSERT_NOT_EQUAL('0', subString->rawString[9]);
TEST_ASSERT_EQUAL(5, oneLineString.startIndex);
TEST_ASSERT_EQUAL(5, oneLineString.length);
TEST_ASSERT_EQUAL(0, subString->startIndex);
TEST_ASSERT_EQUAL(5, subString->length);
subString = getWordAndUpdate(&oneLineString, " ,;"); // bad memory access
}

You function getWordAndUpdate modify your object oneLineString in theses lines of code:
line->length--;
line->startIndex++;
So, when you call it a second times, your object in not consistent.
Try to make a copy of oneLineString or find an algo that not modify your parameter.
Maybe, you can use this kind of function:
String *subString;
String *getWordAndUpdate(String *line, char *delimiter) {
String *word = malloc(sizeof(String));
int i;
for (i = 0; line->rawString[i] != ' '; ++i)
word->rawString[i] = line->rawString[i];
word->length = i;
return word;
}
And you don't take care yet of your delimiter parameter.

Related

Splitting string arrays with delimiter

I'm using the following code to split a char array:
char* Split(char* e, int index) {
index = index -1;
char* v[index +2];
char *p;
int i = 0;
p = strtok(e, ",");
while(p && i < index +2)
{
v[i] = p;
p = strtok(NULL, ",");
i++;
};
// Serial.println(v[0]);
//Serial.println(v[1]);
// Serial.println(v[2]);
return v[index];
};
I'm calling the function like this:
char array[]="1,3,4,55,6,7,66";
Serial.println("array:");
Serial.println(array);
char *out;
out = Split(array,2);
Serial.println("out:");
Serial.println(out);
Serial.println("array:");
Serial.println(array);
out = Split(array,2);
Serial.println("out:");
Serial.println(out);
The first time I call the function, everythin is fine. The result I get is "3" , and that is what I expect.
But with the second call of the function, things goes crazy, and I get just some hieroglyphics.
When I check the variables with the Serial output, I can see that "array" is the second time just "1", and this might be the reason of the curious output of the function.
But I don't understand how the first call of the function can affect the value of "array", because this variable is not touched in the function.
Can anybody help me with clarifying this issue?
The output of the serial interface is lke this:
array:
1,3,4,55,6,7,66
out:
3
array:
1
out:
⸮}⸮a⸮⸮-:⸮⸮⸮m⸮⸮⸮⸮⸮⸮⸮]⸮ʻ⸮T⸮;⸮⸮⸮N}⸮⸮⸮⸮{R⸮U)⸮⸮⸮[G⸮⸮`j⸮⸮⸮⸮⸮v⸮⸮wz⸮⸮s⸮⸮⸮⸮⸮⸮}⸮⸮2⸮⸮vz~⸮⸮⸮⸮O}⸮⸮⸮/⸮⸮nv⸮⸮^j⸮yO⸮7{⸮⸮⸮⸮z⸮Z⸮⸮⸮⸮⸮⸮⸮7[⸮⸮⸮j⸮w⸮⸮⸮⸮⸮⸮⸮w)⸮⸮c⸮⸮}⸮⸮⸮⸮⸮⸮⸮⸮⸮v⸮⸮׺⸮m/V⸮ys<⸮⸮ٿ⸮⸮⸮׆⸮+>ֻ⸮z6⸮=⸮D⸮⸮⸮⸮~⸮⸮⸮⸮e⸮⸮?⸮=⸮⸮W⸮⸮⸮⸮}⸮e⸮ߣN绮⸮w⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮w⸮⸮⸮⸮?⸮⸮⸮⸮⸮⸮⸮Y⸮⸮޴f⸮v⸮⸮u⸮p?⸮⸮^h⸮⸮}⸮⸮ݼ⸮^Wo⸮⸮⸮⸮⸮_⸮⸮⸮⸮⸮⸮;s⸮⸮⸮⸮wZ⸮⸮⸮~⸮7⸮⸮⸮r⸮⸮⸮⸮)⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮f⸮⸮O⸮⸮⸮⸮⸮⸮⸮⸮⸮
⸮⸮7⸮⸮a.⸮⸮.kG⸮⸮8⸮⸮⸮⸮⸮⸮⸮⸮U⸮⸮⸮⸮⸮⸮⸮⸮⸮'⸮we⸮⸮⸮M⸮{⸮⸮Lu⸮no⸮⸮⸮>⸮⸮⸮⸮⸮⸮⸮~}⸮⸮⸮⸮⸮⸮⸮⸮y⸮⸮o⸮⸮⸮,'>}⸮⸮⸮+⸮X⸮⸮⸮/⸮⸮ױ⸮⸮⸮⸮̲⸮⸮-_M⸮⸮⸮⸮L~⸮#Φz~⸮⸮⸮⸮?⸮⸮⸮⸮⸮{/⸮_⸮:⸮jmc⸮m]S⸮_3⸮>o⸮׷⸮ݸv⸮⸮⸮|⸮
⸮⸮{_^⸮⸮o⸮?⸮⸮⸮⸮⸮⸮_⸮⸮⸮⸮{⸮⸮⸮^⸮⸮⸮⸮⸮⸮⸮⸮⸮ퟺ⸮⸮߿⸮⸮p⸮⸮⸮w?=⸮⸮⸮X⸮⸮⸮⸮⸮⸮_⸮oy⸮⸮M⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮w⸮⸮⸮[⸮⸮o⸮⸮⸮⸮޿7wE~⸮⸮⸮⸮⸮N⸮⸮o⸮x⸮=v/⸮⸮⸮⸮>⸮9⸮⸮ί⸮Y_Q⸮⸮l⸮⸮}'⸮⸮}⸮?⸮⸮ޭ⸮6⸮7⸮{⸮T⸮⸮⸮ ⸮r⸮⸮⸮⸮⸮⸮⸮
ܽ+'⸮⸮⸮⸮G⸮f⸮z⸮Gn⸮⸮n⸮/⸮⸮⸮⸮/⸮⸮⸮⸮Q⸮⸮⸮⸮⸮o⸮;⸮L⸮⸮r⸮⸮⸮⸮n/߿ſ⸮⸮⸮⸮q⸮⸮⸮ݮ⸮⸮⸮⸮⸮⸮+⸮⸮⸮⸮⸮⸮ﷹln?⸮⸮⸮⸮q⸮⸮⸮{⸮⸮⸮⸮⸮⸮⸮q⸮-⸮⸮{(⸮⸮f⸮⸮{⸮v⸮܀⸮oq⸮⸮⸮⸮⸮⸮߽⸮⸮nj⸮⸮⸮os⸮6۟g⸮⸮⸮⸮"⸮⸮7Z7⸮⸮yo⸮ӟ⸮⸮⸮w⸮⸮⸮⸮⸮⸮{⸮⸮⸮Vr⸮⸮]_⸮׷SS⸮_⸮w⸮⸮⸮wl⸮⸮⸮⸮P⸮⸮z⸮⸮m{⸮⸮⸮ݛs⸮(⸮⸮r⸮⸮˷:⸮%⸮⸮⸮⸮Z⸮⸮⸮m⸮W⸮⸮⸮⸮ם*⸮⸮⸮[>⸮⸮⸮/⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮?⸮⸮⸮⸮|⸮.⸮⸮⸮{⸮⸮⸮ꍥ⸮⸮⸮|⸮⸮⸮⸮⸮⸮⸮⸮⸮7~Ls⸮!⸮⸮⸮⸮⸮{⸮x⸮g⸮⸮|֍om~~⸮⸮⸮{⸮cϠ⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮>;⸮W⸮⸮⸮⸮⸮⸮⸮⸮q⸮⸮[:⸮'⸮#⸮o⸮⸮_⸮uϾ⸮⸮⸮⸮[⸮⸮^⸮⸮⸮n⸮}⸮⸮⸮⸮⸮>/⸮_⸮⸮-⸮⸮⸮⸮s⸮⸮⸮}⸮⸮⸮⸮/⸮[w⸮⸮r⸮⸮_⸮⸮⸮⸮,⸮⸮ݯ⸮⸮⸮7ÿ⸮:⸮⸮⸮⸮Ί⸮⸮⸮⸮⸮t[|⸮⸮w⸮F⸮⸮⸮
Has anybody a better idea?
The solution depend on your data, if your data is always like a string with list of integers separated with ,, then it will probably better to split it into an int array, you can then write a generic split() function.
#define NUMBER_OF_ELEMENT 7
int splitted[NUMBER_OF_ELEMENT];
const char* delimiter = ",";
void split(const char *str, const char *delimiter) {
char temp[strlen(str)+1] = {0};
memcpy(temp, str, strlen(str));
int i=0;
char *p = strtok(temp, delimiter);
while(p != NULL) {
splitted[i++] = atoi(p);
p = strtok(NULL, delimiter);
}
}
int setup() {
char array[]="1,3,4,55,6,7,66";
Serial.begin(115200);
split(array, delimiter);
// get every splitted element as an int
for (int i=0; i<NUMBER_OF_ELEMENT, i++) {
Serial.print("Out:");
Serial.println(splitted[i]);
}
//if you really want to have string as result
Serial.println(String(splitted[3]));
}
OK I got it by making the array independent from change by strtok:
void setup(){
Serial.begin(115200);
char array[]="1,3,4,55,6,7,66";
char *out;
char array2[8];
strcpy(array2,array);
Serial.println("array2:");
Serial.println(array2);
out = Split(array2,2);
Serial.println("out:");
Serial.println(out);
Serial.println("array3:");
char array3[8];
strcpy(array3,array);
Serial.println(array3);
out = Split(array3,2);
Serial.println("out:");
Serial.println(out);
}
Not that elegant, but it works!!
Has anybody a better idea?
Thanks,great!
Yes my data is always int. So your function is perfect for me.
But for the sake of a clear structure, I would prefer to work with a return value, instead of changing the global variable "splitted".
Is that a good practice? Or do you prefer your variant for saving RAM?
Here my final solution for this task. The function just returns a single value, according to the given index:
int splitStrToInt(char *str, int index) {
//******************
//This function splits a string that is separated by commas and converts the values ​​to int,
//according to the given index
//caution!! The string may only consist of numerical values ​​!!
//Example: "1,3,4,55,6,7,66"
//******************
index--;
char e[strlen(str) + 1] = { 0 };
memcpy(e, str, strlen(str));
int v[index + 2];
char *p;
int i = 0;
p = strtok(e, ",");
while (p && i < index + 2) {
v[i] = atoi(p);
p = strtok(NULL, ",");
i++;
}
;
return v[index];
}

Replace ending of string in C using backwards for loop

I am trying to replace the last part of a string using a for backward for loop iterating for every element of the original string and assigning the first (last elements because I am iterating backwards in the for loop) elements to the string scl = "SCL_10m.tif", and the rest when the counter hits lower than 15, then get all the characters from the string string, and assign them to the newString.
However at the end the result is:
The old string was: S2_2018_08_09_B02_10m.tif
The new string is S2_2018_08_09_B0old string:
Which is different from my expected result:
The new string is S2_2018_08_09_SCL_10m.tif
I don't know what that happened. It supposed to iterate over all the elements of the newString Since it is the same size as the original string. I checked some replace string functions in C, but I wanted to implement something that helps me fast at this particular replace substring in String problem.
Dealing with String in C is very complicated and I am still learning some theory about it, such as: the null Byte and so on. Coming from JavaScript, Python, and Ruby where more of this functions are already implemented in some standard library, I find very hard and at the same time helpful to get the idea of how to implement such algorithms from scratch to deal with specific problems in my code.
I appreciate any idea or hint about what is happening in the code below:
/******************************************************************************
Replace last 11 characters in a longer string
by the values of a smaller (11-char long) string.
*******************************************************************************/
#include <stdio.h>
#include <string.h>
int main()
{
char *string;
string = "S2_2018_08_09_B02_10m.tif";
char *scl;
scl = "SCL_10m.tif";
int length = 0;
int length_scl = 0;
length_scl = strlen(scl);
length = strlen(string);
char newstring[length];
int i;
int cntr = length;
for (i = length; i >= 0; i--)
{
if(cntr > 15){
newstring[i] = scl[i];
cntr--;
}
else if(cntr <= 15)
{
newstring[i] = string[i];
}
}
printf("The old string was: %s\n", string);
printf("The new string is %s:\n", newstring);
return 0;
}
char *func1(char *new, const char *src, const char *repl)
{
size_t src_len, repl_len;
if(src && repl)
{
src_len = strlen(src);
repl_len = strlen(repl);
if(src_len >= repl_len)
{
new[src_len] = 0;
while(repl_len)
{
new[--src_len] = repl[--repl_len];
}
if(src_len)
{
while(--src_len)
{
new[src_len] = src[src_len];
}
}
}
}
return new;
}
char *func2(char *new, const char *src, const char *repl, size_t nchars)
{
//last nchars only (inluding the nul char)
size_t src_len, repl_len;
if(new &&src && repl)
{
new[--nchars] = 0;
src_len = strlen(src);
repl_len = strlen(repl);
if(src_len >= repl_len)
{
while(repl_len && nchars)
{
new[--nchars] = repl[--repl_len];
--src_len;
}
if(src_len && nchars)
{
while(--src_len && --nchars)
{
new[nchars] = src[src_len];
}
}
}
}
return new;
}
int main()
{
char *string = "S2_2018_08_09_B02_10m.tif";
char *repl = "SCL_10m.tif";
char new[256];
printf("func1 - new = \"%s\", src = \"%s\", repl = \"%s\"\n", func1(new, string, repl), string, repl);
printf("func2 - new = \"%s\", src = \"%s\", repl = \"%s\"\n", func2(new, string, repl, 15), string, repl);
printf("func2 - new = \"%s\", src = \"%s\", repl = \"%s\"\n", func2(new, string, "123456789_SCL_10m.tif", 15), string, repl);
return 0;
}

Cannot retrieve all the data from Hashtable

I am trying to code an algorithm in C that reads a huge file ( more than 750.000 lines) , separates each line by some specified delimiters , and saves the data into a structure , which is then saved into a Hashtable. Everything goes fine until I want to print one specific data for each row of the Hashtable: the output is good for some rows , but the console is just printing some random symbols for others (which means memory leaks maybe? ).
I am trying to figure what can cause this problem. If I isolate the code that separate the line and saves it into the structure, and execute it for each line separately, it works fine, everything is printed as expected.
I have also tried to do it without dynamic allocation but it works a bit better with it as I was getting the infamous "Segmentation fault"
Here is the code that splits the line and saves it:
unsigned int hash(unsigned int id) {
unsigned int hashage = 5381; //Valeur arbitraire
unsigned int mdop = 10; //faire un modulo obtenir l'unite
int idtmp = id;
while (mdop < id) {
idtmp = id%mdop;
hashage = ((hashage << 6) + hashage) + idtmp;
mdop *= 10;
}
return hashage % NB_CASES_HASH;
}
void initiate_hashtable(Hashtable hashtable) {
int i = 0;
for (; i < NB_CASES_HASH; i++) {
hashtable[i] = NULL;
}
}
void ajout_entete(Liste *liste, Oeuvre *oeuvre) {
Liste p = malloc(sizeof(Cellule));
if (!p) exit(EXIT_FAILURE);
p->oeuvre = *oeuvre;
p->suiv = *liste;
//Si on imprime ici , tout va bien , les données sont correctes
*liste = p;
}
void ajout_annee(Liste *liste, Oeuvre *oeuvre) { //ajout trié par année pour recherche plus rapide
if (!(*liste) || oeuvre->year <= (*liste)->oeuvre.year)
ajout_entete(liste,oeuvre);
else {
if (oeuvre->year >= (*liste)->oeuvre.year)
ajout_annee(&(*liste)->suiv, &oeuvre);
}
}
Oeuvre peuple_oeuvre(char line[MAX_CHARS_LINE]) {
int i = 0, j = 1, cmpt = 0;
char strings[CHAMPS_OEUVRE][MAX_SIZE];
char carac = *(line);
char mot[MAX_SIZE];
mot[0] = carac;
bool isSuivi = false;
Oeuvre oeuvre;
while (carac != '\n') {
if (carac == ',') {
if(isSuivi) {
mot[j - 1] = '\"';
mot[j] = '\0';
isSuivi = false;
} else
mot[j - 1] = '\0';
strcpy(strings[i], mot);
j = 0;
i++;
} else
if (carac == '\"') {
cmpt++;
carac = *(line + cmpt);
while (carac != '\"') {
mot[j] = carac;
j++;
cmpt++;
carac = *(line + cmpt);
}
isSuivi = true;
}
cmpt++;
carac = *(line + cmpt);
mot[j] = carac;
j++;
}
mot[j] = '\0';
strcpy(strings[i], mot);
//Assignation des valeurs :
oeuvre.id = atoi(strings[0]);
oeuvre.accession_number = strdup(strings[1]);
oeuvre.artiste.nomArtiste = strdup(strings[2]);
oeuvre.artiste.artistRole = strdup(strings[3]);
oeuvre.artiste.artistId = atoi(strings[4]);
oeuvre.titre = strdup(strings[5]);
oeuvre.url = strdup(strings[CHAMPS_OEUVRE]);
oeuvre.year = atoi(strings[9]);
return oeuvre;
}
void peuple_hashtable(Hashtable hashtable) { // Peuplement par redirection
char ligne[MAX_CHARS_LINE];
fgets(ligne, MAX_CHARS_LINE, stdin);
Oeuvre *oeuvre = malloc(sizeof(Oeuvre));
int hashNum;
while (fgets(ligne, MAX_CHARS_LINE, stdin)) {
*oeuvre = peuple_oeuvre(ligne);
hashNum = hash(oeuvre->artiste.artistId);
ajout_annee(&hashtable[hashNum], oeuvre);
}
}
int main() {
Hashtable hashtable;
initiate_hashtable(hashtable);
peuple_hashtable(hashtable);
return 0;
}
And the Oeuvre structure looks like this :
typedef struct oeuvre {
unsigned int id;
char *accession_number;
Artiste artiste;
char *titre;
int year;
char *url;
} Oeuvre;
typedef Liste Hashtable[NB_CASES_HASH];
Thanks in advance.
There are many problems in your code.
If line does not contain a newline or if a double quote is missing, the behavior is undefined.
You do not initialize the string array: if the description has missing fields, the behavior is undefined.
In the part where you save the structure fields, your allocation code is incorrect: you must allocate one more character than the length of the string, strlen(string[0]) + 1 instead of strlen(string[0]) * sizeof(char*).
It would be much simpler to use the POSIX function strdup():
// Assigning the values:
oeuvre.id = atoi(strings[0]);
oeuvre.accession_number = strdup(strings[1]);
oeuvre.artiste.nomArtiste = strdup(strings[2]);
oeuvre.artiste.artistRole = strdup(strings[3]);
oeuvre.artiste.artistId = atoi(strings[4]);
oeuvre.titre = strdup(strings[5]);
oeuvre.url = strdup(strings[CHAMPS_OEUVRE]));
oeuvre.year = atoi(strings[9]);
Solved my issue by declaring the Oeuvre structure like this
typedef struct oeuvre {
unsigned int id;
char accession_number[MAX_CHARS];
Artiste artiste;
char titre[MAX_CHARS];
int year;
char url[MAX_CHARS];
} Oeuvre;
with MAX_CHARS referring to a large number.
So I believe I was not properly allocating the strings before using them, which made them to point to random adresses , resulting in those weird outputs but no error. I also believe that another way of solving this would be to dynamically allocate the chars for each Oeuvre in my function.

C: Returning String From Another Function

I'm new to C / pointers / memory management and am having trouble implementing a few functions for a project I'm working on.
In my builtins.c file, I have a function called printalias that is called to print all the alias names and corresponding values stored in my program. At the end, I want to print one of the alias names by retrieving it via another function called getal.
int x_printalias(int nargs, char *args[]) {
int i = 0;
// Loop through, print names and values
for(i = 0; i< 100; i++)
{
if(alias_names[i][0]!='\0' && !alias_disabled[i])
{
char * var = alias_names[i];
char * val = alias_vals[i];
fprintf(stderr,"%s = %s\n", var, val );
}
}
// This is where I want to retrieve the string from another function
char * hello = "brett";
hello = getal(hello);
fprintf(stderr,"Got alias for brett --> %s",hello);
return 0;
}
My getal function exists in my shellParser.c file and looks like this, generally performing the same looping and returning when it is found:
const char * getal(int nargs, char *args[])
{
fprintf(stderr,"\nRetrieving alias...\n");
int i = 0;
fprintf(stderr, "check1\n" );
fprintf(stderr,"Got args[0]: %s\n", args[0]);
while (alias_names[i][0]!='\0' && i < MAX_ALIAS_LENGTH ) // Find empty slot in variables array
{
fprintf(stderr, "check2\n" );
fprintf(stderr,"I is currently %i and current varible in slot is %s\n",i,alias_names[i]);
//strncpy(hello, variables[i], MAX_VAR_LENGTH); // Variable at current slot
if(strcmp(alias_names[i], args[0]) == 0) // If we have an entry, need to overwrite it
{
fprintf(stderr,"Found alias %s = %s at spot %i\n",args[0],alias_vals[i], i); // Not at end if here
return alias_vals[i];
}
i++;
}
fprintf(stderr, "check3\n" );
// Elided....
return '\0';
}
In the end of my printalias function, I want to test that this getal function is working by calling it on a hardcoded string "brett". However, when I call my printalias function from the command line, it makes it to the "Check 1" print statement and then simply quits without error or return value.
I think this has something to do with my memory management or incorrect declaration of variables with pointers. Can anybody spot something (or a lot of things) that I'm doing wrong here?
You must declarete list of argument for to call getal and it call with these
list.
And pointer of return values getal must be const char*
//....
// This is where I want to retrieve the string from another function
char * hello[] = {"brett"}; // this list argument for getal function
const char *strGetal;
strGetal = getal(1,hello);
fprintf(stderr,"Got alias for brett --> %s",strGetal);
return 0;
}
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** get_all(int argc, char **argv)
{
char *value;
char **values = NULL;
int i;
values = (char**) malloc(sizeof (char) * argc);
if (values == NULL) {
perror("malloc");
return NULL;
}
for (i = 0; i < argc; i++, argv++) {
value = strchr(*argv, ':');
values[i] = (value + 1);
}
return values;
}
int main()
{
char *args[] = {"key:a", "key:b", "key:c"};
char **values;
int i;
values = get_all(3, args);
for (i = 0; i < 3; i++) {
puts(values[i]);
}
return 0;
}

using functions in c (return value)

Learning C and having many doubts.
I have a function (lets say function 1) that calls another function (lets say function 2).
Function 2 calculates an array of string.
How can I use this array in function 1?
Some code example:
int find_errors(char* word)
{
char error[100];
/*Given the word, It will find the duplicate chars and store it in the
error array. */
return 0;
}
int find_word(char* word)
{
find_errors (word);
printf("%s\n", error);
return 0;
}
There are at least three possible approaches:
Use a global variable
pass a parameter between them
return a pointer from the function
There are multiple ways to do this.
1) Create a dynamic array and return a pointer to the array. This will require you to manually free the memory for the array at a later time.
#define NUM_ELEMS 50
// In find_error():
char* error = malloc(NUM_ELEMS * sizeof(char));
return error;
// In find_word():
char *error = find_errors();
// do stuff
free(error);
2) Pass a pointer to find_errors that it can use as the error array. This will not require you to manually free the memory.
// In find_word():
char error[NUM_ELEMS];
find_error(error);
3) Use a global array. May make it more difficult for other people to understand your code. Has other potential problems as well.
// In global scope:
char error[NUM_ELEMS];
Your question relates to "call-by-reference" and "call-by-value".
char* getNewValsToSet(void)
{
char* new_vals = (char*) malloc(sizeof(char[5]));
new_vals[4] = '\0';
return new_vals;
}
void setValuesEven(char* vals_to_set)
{
vals_to_set[0] = 'A';
vals_to_set[2] = 'C';
}
void setValuesOdd(char* vals_to_set)
{
vals_to_set[1] = 'B';
vals_to_set[3] = 'D';
}
int main(void)
{
char* some_vals_to_set = getNewValsToSet();
setValsEven(some_vals_to_set);
setValsOdd(some_vals_to_set);
// ... now has vals "ABCD"
free(some_vals_to_set); //cleanup
return 0;
}
If you have "doubts" about learning C, IMHO it's one of the best things you can do (no matter the language in which you work) because it will explain exactly how things work "under-the-hood" (which all high-level languages try to hide to some degree).
You need to declare the error array globally and use it just like you did.
EDIT: using global variables isn't the best practice in most of the cases, like this one.
Here is an example of what you are looking for with an awesome console output. It dynamically allocates the array to hold any number errors (duplicate characters in your case) that may occur.
//Only free errors if result is > 0
int find_errors(char* word, char** errors)
{
int num_errors = 0;
int word_length = strlen(word);
int ARRAY_SIZE = MIN(8, word_length);
char existing[word_length];
int existing_index = 0;
*errors = NULL;
for(int i = 0; i < word_length; i++)
{
char character = word[i];
//Search array
for (int n = 0; n < word_length; ++n ) {
if(n >= existing_index)
{
existing[n] = character;
existing_index++;
break;
}
if (existing[n] == character) {
num_errors++;
if(!*errors)
*errors = (char*)malloc(ARRAY_SIZE * sizeof(char));
//Check if we need to resize array
if(num_errors >= ARRAY_SIZE)
{
ARRAY_SIZE *= 2;
ARRAY_SIZE = MIN(ARRAY_SIZE, word_length);
char *tmp = (char*)malloc(ARRAY_SIZE * sizeof(char));
memcpy(tmp, *errors, (unsigned long)ARRAY_SIZE);
free(*errors);
*errors = tmp;
}
//Set the error character
(*errors)[num_errors - 1] = character;
break;
}
}
}
return num_errors;
}
int find_word(char* word)
{
char* errors;
int errCount = find_errors (word, &errors);
if(errCount > 0)
{
printf("Invalid Characters: ");
for(int i =0; i < errCount; i++)
{
printf("%c ", errors[i]);
}
printf("\n");
free(errors);
}
return 0;
}
int main(int argc, char *argv[])
{
find_word("YWPEIT");
find_word("Hello World");
find_word("XxxxXXxXXoooooooOOOOOOOOOOOOOOOooooooooOOOOOOOOOOOOooooooOOO");
}

Resources