Everytime I declare I function, my variable made by the function changes. C Language - c

so I am working on my Binary adding program, but now I am stuck. I want to declare 2 variables for the first binary and second one, so I use the getBinary function I created to declare these 2. However, after I entered value for firstBin, I got the value I want, but after I entered the value for secBin, the value of firstBin somehow changes and become the same as secondBin. I was hoping for the variable to be unchangable. Thanks for the help
#include <stdio.h>
int * getBinary(){
int i;
int j;
static int first8bits[8];
for (i = 0; i != 8; i++){
printf("Input 8-bits Binary:");
scanf("%d",&first8bits[i]);
}
for (j = 0; j != 8; j++)
printf("%d",first8bits[j]);
printf("\n");
return first8bits;
}
int main(){
int o;
printf("Input the first Set of Binary...");
const int * firstBin = getBinary();
printf("Input the second Set of Binary...");
int * secBin = getBinary();
for (o = 0; o != 8; o++)
printf("%d",firstBin[o]);
}

Because of the static keyword.
Don't use static. Try:
int* first8bits = malloc(8 * sizeof(int));
This way you will allocate new memory each time you call it. You can still access it with the same [ i ] subscript. Remember to free the memory again at the end of main!
free(firstBin);
free(secBin);

Related

Function that returns 1D array and writes the results to a text file

I've been asked to write a code that takes 2, 1D arrays from a text file, add them and then return the results to another text file. Yet, I still get errors about pointers. I'm a C newbie and I'll be very happy if someone could explain it to me.
int result(int a[], int b[])
{
int *wsk = &c_tab[0];
char choice;
printf("0.Add\n1.Substract");
scanf("%c", &choice);
for (i=0; i<9; i++) {
if (choice== '0')
{
*wsk = a[i] + b[i];
wsk++;
}
else if (choice== '1')
{
*wsk = a[i] - b [i];
wsk++
}
}
return *wsk;
}
The first error I see is that you need to declare the function type with the type of the returned value, in this case the function has to be:
int *dzialanie(int a[], int b[]){
...
return wsk;
}
Another error is in the for loop, the operation has to be:
...
for (int i=0; i<9; i++){
*(wsk + i) = a[i] + b[i];
}
...
Same for the another (See that you didn't declare the i which is a variable too). Another way, is doing:
wsk[i] = a[i] - b[i];
Is the same.
If you already know the dimension of the two arrays, maybe is better to take the arguments as pointers, it will look like:
int dzialanie(int *a, int *b){
...
}
And you will have to allocate memory, this coul be done with malloc:
wsk = (int *)malloc(10*sizeof(int));
At the end of your program you will want to free that allocated memory, doing:
free(wsk);
Hope you understand, my english is poor, I'm from Argentina. Greetings!
since you are using a global variable the return type should be void(and or some form of indication that the calculation has been done. which in turn could be a simple return value of -1 or w/e(i'll leave that part up to you).
int res[10]; // global variable
void add(int *a, int *b) // no return value, new array will be saved globally(not advisable)
{
int sign = -1; // your +- check
printf("0.Suma\n1.Roznica");
scanf("%c", &sign);
if (sign == 0)
{
for (int i = 0; i < 9; i++)
res[i] = a[i] + b[i];
}
else if (sign == 1)
{
for (int i = 0; i < 9; i++)
res[i] = a[i] - b[i];
}
}
an alternative way of doing it would be to use either a or b as "return" values with a simple change like a[i] += b[i] -> now a has the value of a + b. this way you won't have to deal with pointers going out of scope etc(documentation of how to return pointers from functions(in a safe way) is here).

Assigning point to customer C programming

I would like to get assistance in my coding. I created a customer loyalty system using C (using file) and now I need to assign some called points to my customer, but what happenned is it will not assign any points to them.
{
for (int i = 0; i < (count / 3); i++)
{
fscanf(reward_file, "%s\n%s\n%d\n", user[i].Username, user[i].Password, &user[i].Points);
if (Point = user[i].Points)
{
strcpy(user[i].Points, Reward);
Point = Point + Reward;
printf("%d", Point);
system("pause");;
}
}
fclose(reward_file);
FILE *new_file = fopen("CustomerRegistration.txt", "w");
for (int i = 0; i < NumOfCust; i++)
{
fprintf(new_file, "%s\n%s\n%d\n", user[i].Username, user[i].Password, user[i].Points);
}
fclose(new_file);
printf("You Have Successfully Added Your Point!!!\n");
printf("You Will be Redirected Back to Customer Privilege Menu");
system("TIMEOUT \t 5");
}
I am using struct for my customer and here is the code
struct USER
{
char Username[255];
char Password[255];
int Points;
};
struct USER user[100];
Data is obtained from a function called "Login"
FILE *LOGINFILE = fopen("CustomerRegistration.txt", "r");
if (LOGINFILE)
{
system("cls");
printf("!!!Hello Customer!!!\n");
printf("Please type in your Username and Password\n");
printf("Username\t: ");
//while ((c = getchar()) !='\n');
gets(UN);
printf("Password\t: ");
gets(Pswd);
I also assigned global variable called "Point"
int Point = 0;
Your help will be highly appreciated.
From what I am understanding from your posted code you want to add a Reward to the Customer Points.
Firstly you just need to add to user.Points the Reward, using strcpy makes no sense because that function is used for copying strings.
that if( Point = user[i].Points ) also makes no sense firstly because C equality condition is represented by a double equal sign ( "==" ) and you don't need to make that check.
The .Points member is an int and Reward is also an int ,so you can do arithmethic operations and there is no need to use another Point auxiliar.
for (int i = 0; i < (count / 3); i++)
{
fscanf(reward_file, "%s\n%s\n%d\n", user[i].Username, user[i].Password, &user[i].Points);
user[i].Points += Reward;
printf("%d", user[i].Points);
system("pause");;
}
.....
the first loop:
for (int i = 0; i < (count / 3); i++)
the second loop
for (int i = 0; i < NumOfCust; i++)
if NumOfCust is greater than (count/3)) you'll get unitialized values on CustomerRegistration.txt. I can't see the values of those variables, but make sure it doesn't happen. The best would be to use the last value of i in the first loop to the stop condition for the second loop.

Having trouble making memset function?

void memSet(char destination[], char valueMemSet, int numOfValue)
{
char temp;
int j=1;
for (int i = 0; i <= numOfValue; i++)
{
temp = destination[i];
destination[i] = valueMemSet;
destination[j] = temp;
j++;
}
}
The array is originally "this is the source Concatenate means to link."
This is what I am trying to get "------this is the source Concatenate means to link."
This is What I am currently getting "-------Tthe source Concatenate means to link."
When I ran the debugger it saves the first letter of the array but every single one after gets replaced.
How can I solve this issue?
memset() is a function, which sets a particular value in a given memory, like you want to initialize total array's elements to some particular value(for eg - zero). So it will set the same in that array.
what you need here is strcat() function.
Is that what you need?
void memSet(char destination[], char valueMemSet, int numOfValue, int len)
{
int j=len-numOfValue;
for (int i = len-1;i>=numOfValue;i--) {
destinstion[i] = destination[j--];
}
for (int i = 0; i < numOfValue; i++)
{
destination[i] = valueMemSet;
}
}

Realloc no execute

First of all,the names of variables are in greek.
It's impossible to saw all the code,because is many files.
However a have a struct
typedef struct{
TTamias* Tamies;
}TPinakasTamiwn;
And TTamias is type
typedef struct{
int time_busy; /*xronos apasxolhshs tou tamia*/
int time_inactive; /*xronos pou o tamias einai adranhs*/
int arithos_pelaton; /*posous pelates eksipiretise o tamias*/
int enapomenon_xronos; /*enapomenon xronos eksipiretisi enos pelath*/
}TTamias;
With this function in main i create an array
void DimourgiaTamiwn(TPinakasTamiwn* tamias)
{
tamias->Tamies = (TTamias*)malloc(sizeof(TTamias) * TAMIES);
}
After some comparisons i want to raise the size of array with this function
int ProsthikiTamia(TPinakasTamiwn* tamias,int plithos_tamiwn)
{
TTamias* NeoiTamies;
int neo_plithos = plithos_tamiwn + 1;
NeoiTamies = (TTamias*)malloc(sizeof(TTamias) * neo_plithos);
for(int i = 0; i < plithos_tamiwn; i++)
NeoiTamies[i] = tamias->Tamies[i];
for(int i = neo_plithos - plithos_tamiwn; i < neo_plithos; i++)
TamiasDimiourgia(&NeoiTamies[i]);//fuction to initialize the data member of extra index
tamias->Tamies = (TTamias*)realloc(tamias->Tamies , neo_plithos);// <-----PROBLEM
for(int i = 0; i < neo_plithos; i++)
tamias->Tamies[i] = NeoiTamies[i];
free(NeoiTamies);
return neo_plithos;
}
The function return the new size that is raise than one.
I create a local array and copy to that the main array,
i want to reallocate the main array and copy again the local array to new main array.
Doesn't appear compile error,but in execution (also at debug) the program break at realloc.
When reallocating, you have forgotten to multiply the dimension by the unit size. The correct line shall be:
tamias->Tamies = (TTamias*)realloc(tamias->Tamies , sizeof(TTamias) * neo_plithos);

What's wrong in this C program..?

struct bucket
{
int nStrings; //No. of Strings in a Bucket.
char strings[MAXSTRINGS][MAXWORDLENGTH]; // A bucket row can contain maximum 9 strings of max string length 10.
};//buck[TOTBUCKETS];
void lexSorting(char array[][10], int lenArray, int symb) //symb - symbol, sorting based on character symbols.
{
int i, j;
int bucketNo;
int tBuckNStrings;
bucket buck[TOTBUCKETS];
for(i=0; i<lenArray; i++)
{
bucketNo = array[i][symb] - 'a'; // Find Bucket No. in which the string is to be placed.
tBuckNStrings = buck[bucketNo].nStrings; // temp variable for storing nStrings var in bucket structure.
strcpy(buck[bucketNo].strings[tBuckNStrings],array[i]); // Store the string in its bucket.
buck[bucketNo].nStrings = ++tBuckNStrings; //Increment the nStrings value of the bucket.
}
// lexSorting(array, lenArray, ++symb);
printf("****** %d ******\n", symb);
for(i=0; i<TOTBUCKETS; i++)
{
printf("%c = ", i+'a');
for(j=0; j<buck[i].nStrings; j++)
printf("%s ",buck[i].strings[j]);
printf("\n");
}
}
int main()
{
char array[][10] = {"able","aback","a","abet","acid","yawn","yard","yarn","year","yoke"};
int lenArray = 10;
int i;
printf("Strings: ");
for(i=0; i<lenArray; i++)
printf("%s ",array[i]);
printf("\n");
lexSorting(array, lenArray, 0);
}
Well here is the complete code, that I am trying. since its been a long time since i have touched upon C programming, so somewhere i am making mistake in structure declaration.
The problem goes here:-
1) I have declared a structure above and its object as array(buck[]).
2) Now when I declare this object array along with the structure, it works fine.. I have commented this thing right now.
3) But when I declare this object array inside the function.. because ultimately i have to declare inside function( as i need to build a recursive program, where objects will be created in very recursive call) then the program is throwing segmentation fault.
Expected Output
> [others#centos htdocs]$ ./a.out
> Strings: able aback a abet acid yawn
> yard yarn year yoke
> ****** 0 ******
> a = able aback a abet acid
> b =
> c
> .
> .
> y = yawn yard yarnyear yoke
> z =
Actual Output
[others#centos htdocs]$ ./a.out
Strings: able aback a abet acid yawn yard yarn year yoke
Segmentation fault
I have no idea, what difference I made in this. Kindly help.
Thanks.
What's wrong with your program is that it doesn't contain a main() function hence it won't link.
Beyond that, you should always do the following when asking questions here:
Provide a complete, minimal code sample that demonstrates the problem.
Detail the expected behaviour.
Detail the actual behaviour.
In fact, when I add the line:
int main (void) { return 0; }
it compiles and links fine.
That means it's almost certainly a run-time error you're experiencing hence we need the main() to figure out what you're doing wrong.
Using my psychic debugging skills, an important difference between declaring it at file scope and block scope is that the file-scope version will be initialised to zeros.
That means all the structure fields will be effectively zero (for the count) and empty strings (for the strings). With block scope, those counts and strings will be uninitialised.
The fact that you're using TOBUCKETS to print the structure out probably means you're trying to print out one of those uninitialised strings.
I think what's probably happening is that the nStrings field contains a garbage value when you start the processing. You should probably initialise it to zero manually (with a loop) and see if that fixes your problem. Put this after the declaration of buck in your sort function:
for (i = 0; i < TOTBUCKETS; i++)
buck[i].nStrings = 0;
Right. It turns out that was the problem. When I fix up the errors in your latest code, I get the segmentation violation as well but, when I add that section above, it works fine:
#include <stdio.h>
#include <string.h>
#define MAXSTRINGS 9
#define MAXWORDLENGTH 10
#define TOTBUCKETS 26
struct bucket
{
int nStrings;
char strings[MAXSTRINGS][MAXWORDLENGTH];
};
void lexSorting(char array[][10], int lenArray, int symb)
{
int i, j;
int bucketNo;
int tBuckNStrings;
struct bucket buck[TOTBUCKETS];
for(i=0; i<TOTBUCKETS; i++) buck[i].nStrings = 0;
for(i=0; i<lenArray; i++)
{
bucketNo = array[i][symb] - 'a';
tBuckNStrings = buck[bucketNo].nStrings;
strcpy(buck[bucketNo].strings[tBuckNStrings],array[i]);
buck[bucketNo].nStrings = ++tBuckNStrings;
}
printf("****** %d ******\n", symb);
for(i=0; i<TOTBUCKETS; i++)
{
printf("%c = ", i+'a');
for(j=0; j<buck[i].nStrings; j++)
printf("%s ",buck[i].strings[j]);
printf("\n");
}
}
int main()
{
char array[][10] = {"able","aback","a","abet","acid",
"yawn","yard","yarn","year","yoke"};
int lenArray = 10;
int i;
printf("Strings: ");
for(i=0; i<lenArray; i++)
printf("%s ",array[i]);
printf("\n");
lexSorting(array, lenArray, 0);
}
The output of that was:
Strings: able aback a abet acid yawn yard yarn year yoke
****** 0 ******
a = able aback a abet acid
b =
c =
d =
e =
f =
g =
h =
i =
j =
k =
l =
m =
n =
o =
p =
q =
r =
s =
t =
u =
v =
w =
x =
y = yawn yard yarn year yoke
z =
keyword struct is not required when you create objects for it.

Resources