So I was trying to use a global pointer that I define in a function and I'm going to use in another function without passing as parameters.
Here is my fun.c file
#include <stdio.h>
#include <stdlib.h>
int *step;
int step_counter;
int init(int num){
step = #
step_counter = *step;
return 0;
}
void reset_counter(){
step_counter = *step;
printf("%d ", step_counter);
}
Here is the main.c file
#include <stdio.h>
#include <stdlib.h>
#include "fun.c"
int main()
{
init(3);
reset_counter();
return 0;
}
I was expecting that the reset_counter function to print 3. But instead it prints out 0. I don't know what's the problem. I'm pretty new to C.
You have undefined behavior.
You point step to the address of num but num is a local variable that's destroyed after init() returns. Trying to derefence step in reset_counter() gives you UB as what it's pointing to is already destroyed.
Why are you using a pointer for step? You could just use step = num; and have step be an int.
In this function
int init(int num){
step = #
step_counter = *step;
return 0;
}
parameter num is a local variable of the function. After exiting the function the variable will not be alive and its memory can be reused by some other parts of the program.
As result the pointer step will have an invalid value and the program will have undefined behavior if it'll try to access the memory pointed to by the pointer.
You could rewrite the function the following way.
int init(int num){
step = malloc( sizeof( *step );
int success step != NULL;
if ( success )
{
*step = num;
step_counter = *step;
}
return success;
}
You should not forget to free the pointer before exiting the program.
Though it is not clear why you need the additional variable step_counter.
I would rewrite the code snippet the following way
int *step;
int init(int num){
step = malloc( sizeof( *step ) );
int success = step != NULL;
if ( success ) *step = num;
return success;
}
void reset_step(){
free( step );
step = NULL;
}
Related
basically returning the value straight as "return pow((n%10),3) + arms(n/=10);" works but not passing it through another variable?
#include <stdio.h>
#include <math.h>
void arms(int n){
int temp;
if (n!=0){
temp = pow((n%10),3) + arms(n/=10);
}
(temp==n)?printf("ARMS"):printf("NO ARMS");
}
int main() {
arms(153);
return 0;
}
arms is void which means that it does not return anything, yet you try to use it in your calculation:
temp = pow((n%10),3) + arms(n/=10);
^^^^^^^^^^^^^^
This is not valid. The compiler can't add void to pow(%n%10,3).
A void function doesn't return anything but you as a programmer can't use it and expect the compiler to do the work for you, which in this case would be to remove the call to arms:
temp = pow((n%10),3);
I am new to C language somehow and I am trying here to call a function "func" in main function but it gives me compiling error. I tried to search for examples similar to this situation in Google but stil getting errors.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
struct str {
int value;
uint32_t ptr_next;
};
void func(int arg, char* arr[]);
int main() {
int Arg;
char* Arr[1];
func(Arg, *Arr[1]);
return 0;
}
void func(int arg, char* arr[]) {
int list;
struct str r;
FILE* file = fopen(arr[1], "rb");
do {
list = fread(&r, sizeof(struct str), 1, file);
if (list > 0)
printf("%d ", r.value);
fseek(file, r.ptr_next, 0);
}
while ((r.ptr_next != 0) && (list > 0));
}
The question is how can I call functions by value in C language?
C only supports calling functions by value, calling by reference was added in C++ and uses the & symbol.
The value you are passing to the function is a location in memory, a pointer. If you want to hand to the function a copy of the data at that memory location you'll need to make a copy for it.
// Assuming that Arg and Arr are initialized.
char* Arr2[]; // Make a storage place for the char**.
Arr2 = malloc(Arg*sizeof(char*)); // Make the right number of char*s in it
for(int e=0; e<Arg; e++) { // For each elem in the main array:
Arr2[e]=malloc(sizeof(char)*strlen(Arr[e])); // Make space for the chars,
strcpy(Arr2[e],Arr[e]); // And copy them.
}
Side note
You haven't initialized Arg or Arr in main. I suspect that you might have meant the command line parameters.
int main(int Arg, char* Arr[])
I'm writing a program that's running on an embedded MCU, so all of my memory allocations are to the stack (no malloc()). I have a struct being created in a function and returned to a caller, and I'm trying to keep a reference to that variable in an array, prior to being returned.
The problem is that the variable stored in the array seems to be a copy of the variable returned to the caller, so they're not in sync. The code below illustrates the issue:
#include <stdio.h>
int *ARRAY_OF_VARIABLES[1];
int initalizeVariables() {
int i = 0;
ARRAY_OF_VARIABLES[0] = &i;
return i;
}
int main(void)
{
int test = initalizeVariables();
test = 1;
printf ("Test: %d, ARRAY_OF_VARIABLES[0]: %d\r\n", test, (int)*ARRAY_OF_VARIABLES[0]);
}
This prints: Test: 1, ARRAY_OF_VARIABLES[0]: 0
How can I keep "test" and "ARRAY_OF_VARIABLES[0]" in sync without malloc() and pointers?
I solved this by creating a function that I can pass a pointer of i back into for storage in ARRAY_OF_VARIABLES. Here's the new code:
#include <stdio.h>
int *ARRAY_OF_VARIABLES[1];
int initalizeVariables() {
int i = 0;
return i;
}
void setInArray(int *i, int idx) {
ARRAY_OF_VARIABLES[idx] = i;
}
int main(void)
{
int test = initalizeVariables();
setInArray(&test, 0);
test = 123;
printf ("Test: %d, ARRAY_OF_VARIABLES[0]: %d\r\n", test, *ARRAY_OF_VARIABLES[0]);
}
If there are any better ways to do this, please feel free to post them :).
I have a project in which I have to make a basic database in C. My problem lies that keep passing a variable n from function to function and at one point the value changes.
I have made a test program which illustrates the same issue I'm having:
#include <stdio.h>
#include <stdlib.h>
void functionTWO(int *n)
{
printf("\n%d",*n);
}
functionONE(int *n)
{
int i=0;
i++;
i++;
*n = i;
printf("\n%d", *n);
functionTWO(&n);
}
int main()
{
int n=0;
printf("%d",n);
functionONE(&n);
return 0;
}
The n in the second function is displayed as a very very high number, e.g.:
0
2
2752268
Now, I know this probably is intended, but could you guys kindly explain why this happens this way?
In your functionONE(), n is already a pointer. You don't need to pass the address of the pointer if you intend to change that value-at-the-address.
As an advice, always check the data types and enable the compiler warnings to help you.
functionONE()
your are passing a address of address. So it's printing address of n.
Now you want a correct output then n as double pointer **n.
void functionTWO(int **n)
{
printf("\n%d",**n);
}
First of all, in C int & n is not the reference of n, it is it's address.Now, what you've done is created an int - sent it's address to functionONE - did something to the value in that address and then sent the the argument's address to functionTWO, instead of sending the argument itself, becuase it's already a pointer. Do this instead:
#include <stdio.h>
#include <stdlib.h>
void functionTWO(int *n)
{
printf("\n%d",*n);
}
functionONE(int *n)
{
int i=0;
i++;
i++;
*n = i;
printf("\n%d", *n);
functionTWO(n); // <-- send the pointer, not it's address
}
int main()
{
int n=0;
printf("%d",n);
functionONE(&n);
return 0;
}
In functionONE, n is int *, just a pointer, when you do functionTWO(&n);, you get the address of n, so it output a big value.
The value being printed in functionTWO function is the address of the pointer variable n declared in functionONE.In that case you can either modify functionTWO like this
void functionTWO(int **n)
{
printf("\n%d",**n);
}
or
Just pass the value of the pointer variable like this
functionTWO(n);
I keep geeting a segfault in the main function. I create a pointer to a struct I created and I pass it's reference to another function which allocates and reallocates memory. Then accessing it in the main function (where it was originally defined) causes a segfault.
Here is my test code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct {
char desc[20];
int nr;
} Kap;
void read(Kap *k);
int main(void) {
Kap *k = NULL;
read(k);
printf("__%s %d\n", k[4].desc, k[4].nr);
return 0;
}
void read(Kap *k) {
int size = 3;
k = (Kap*) calloc(size, sizeof(Kap));
k[0].nr = 1;
k[1].nr = 2;
k[2].nr = 3;
strcpy(k[0].desc, "hello0");
strcpy(k[1].desc, "hello1");
strcpy(k[2].desc, "hello2");
size *= 2;
k = (Kap*) realloc(k, sizeof(Kap)*size);
if(k == NULL) {
printf("ERROR\n");
exit(EXIT_FAILURE);
}
k[3].nr = 4;
k[4].nr = 5;
k[5].nr = 6;
strcpy(k[3].desc, "hello3");
strcpy(k[4].desc, "hello4");
strcpy(k[5].desc, "hello5");
}
What am I doing wrong?
Here's a simplified version of the problem you are having:
#include <stdio.h>
void func(int x)
{
x = 10;
}
int main()
{
int x = 5;
printf("x = %d\n", x);
func(x);
printf("x = %d\n", x);
}
The same reason x does not change is the reason that k does not change in your program. A simple way to fix it is this:
Kap *read()
{
Kap *k = calloc(...);
...
k = realloc(k, ...);
...
return k;
}
int main()
{
Kap *k = read();
...
}
The problem is you're not passing the pointer back to main(). Try something like this instead:
Kap * read();
int main(void) {
Kap *k = read();
printf("__%s %d\n", k[4].desc, k[4].nr);
return 0;
}
Kap * read() {
... everything else you're already doing ...
return k;
}
The code you showed passes a pointer by value into read(). The subroutine can use that pointer (though it's kind of useless since its local copy is immediately changed), however changes made within read() do not bubble back to its caller.
My suggestion is one method of allowing read() to send the new pointer back up, and it's probably the right method to choose. Another method is to change read()s signature to be void read(Kap **);, where it will receive a pointer to a pointer -- allowing it to modify the caller's pointer (due to being passed by reference).