gpt4 book ai didi

c - 在C中使用数组打印特定值

转载 作者:行者123 更新时间:2023-11-30 17:43:07 25 4
gpt4 key购买 nike

我对C语言真的很陌生。需要一些有关如何使用数组打印特定值的帮助,如下所述。

这是我的数组声明:

这里guestArray获取了tid的所有值

long guestArray[10]= {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
int l = 0;
void *guest(void *threadid)
{
long tid ;
tid = (long)threadid;
guestArray[l]= tid;
l++;
}

tid 的值为 1-10

但是当我在其他函数中使用该数组时,它会打印 tid 以外的值

void *checkOut()
{
int j;
for (j = 0 ;j<10;j++)
{
printf("Guest %d \n" , guestArray[j]);
}

最佳答案

您的函数 guest 似乎不知道 l 并且它正在将 tid 分配给任何地方。这会调用未定义的行为,您将得到任何结果,无论是预期的还是意外的结果。

另一个问题是函数的返回类型是 void * 但你没有从中返回任何内容。您的编译器应该对此发出警告。

<小时/>

编辑:根据 link由OP给出;
您使用了错误的说明符 %d 来打印 tid 的值。 %d 用于 int 类型,但 tidlong int 类型。使用错误的说明符会调用未定义的行为,您将得到任何结果,无论是预期的还是意外的结果。使用 %ld 表示 lon 类型。

7.21.6 格式化输入/输出函数:

If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior isundefined.

关于c - 在C中使用数组打印特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304942/

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