Shou Barrett
Shou Barrett

Reputation: 61

How do I declare a pointer with a constant variable

Below is my code: When I run it, I get the following statements:

X is equal to 1 and k is equal to 1 
X is equal to 0 and k is equal to 0 

What I wish to achieve is to have both statements stating the same thing (equal to 1). I understand I can just set the integers x, and k respectively to 1 underneath the if statement, however I want to know how to store a value after the function is executed, so that x and k remain equal to one after execution of the second function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void run_times( int runs);

int main (){
    int i;

    while ( i <3) {
        run_times(i);
        printf("Looped\n");
        i++;
    }
}

void run_times( int runs) {
    int *x,k;

    if (runs == 0) {
        x = &k;
        *x = 1;
        printf("X is equal to %d and k is equal to%d\n", *x, k);
    }   
    if (runs == 1){
        printf("X is equal to %d and k is equal to%d\n", *x, k);
    }

Thanks in advance

Upvotes: 1

Views: 47

Answers (2)

Piotr Praszmo
Piotr Praszmo

Reputation: 18320

You can achieve that by making k static (there is really no need for the pointer in this case). The result will be similar to global variable - which are generally a bad idea. Usually it makes more sense to make the declaration local:

void run_times(int *x, int runs) {
    printf("x is equal to %d\n", *x);
    if (runs == 0) {
        *x = 1;
    }   
}

This way it will still work, if you ever decide you need two separate states:

int main() {
    int k0 = 0;
    int k1 = 2;
    int i = 0;
    while ( i <3) {
        run_times(&k0, i);
        run_times(&k1, i);
        i++;
    }
}

It should be also clearer to the reader, as you are not passing data via hidden variables.

Upvotes: 0

weston
weston

Reputation: 54781

void run_times( int runs) {
    static int *x,k;

A static variable means that variable keeps its values between invocations.

Note that the code as asked is running with uninitialized local variables, which is undefined behavior. So it may or may not work anyway, IDE one runs as you want it to without any changes! http://ideone.com/X7dqHr

Note that we do not have that problem with static variables as they are initialized to zero. See: Why are global and static variables initialized to their default values?

Upvotes: 1

Related Questions