gpt4 book ai didi

c - 如何声明一个带有常量变量的指针

转载 作者:太空宇宙 更新时间:2023-11-04 03:35:57 26 4
gpt4 key购买 nike

下面是我的代码:当我运行它时,我得到以下语句:

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

我希望实现的是让两个语句都陈述同一件事(等于 1)。我知道我可以在 if 语句下将整数 x 和 k 分别设置为 1,但是我想知道如何在函数执行后存储一个值,以便在执行第二个函数后 x 和 k 保持等于 1功能。

#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);
}

提前致谢

最佳答案

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

static 变量意味着该变量在调用之间保持其值。

请注意,所要求的代码是使用未初始化的局部变量运行的,即 undefined behavior .所以它可能会或可能不会工作,IDE one 可以按照你想要的方式运行,无需任何更改! http://ideone.com/X7dqHr

请注意,我们没有 static 变量的问题,因为它们被初始化为零。请参阅:Why are global and static variables initialized to their default values?

关于c - 如何声明一个带有常量变量的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32800306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com