gpt4 book ai didi

c - 声明数组并在两种不同的方法中使用它 - C

转载 作者:行者123 更新时间:2023-11-30 19:58:49 25 4
gpt4 key购买 nike

我对 C 比较陌生。我有一个问题:我可以全局声明一个数组,然后在一种方法中更改其值,然后在其他方法中使用更改后的值吗?

喜欢,

int array[5] = {11,12,13,14,15}
void somemethod()
{
//Changing Array Values
}

void somemethod2()
{
int k;
for(k= 0; k<5;k++)
printf ("New Value of Array %d" , array[k])
}

我问这个是因为我做了与上面代码类似的事情,但唯一的问题是当我想打印出数组的新值时,它只打印出k的值 ,即 0,1,2,3,4

最佳答案

您的代码存在问题 - 您提供了指向 ( http://codepad.org/Eo7KTFY9 ) 的链接:

for(t=0;t<NUM_THREADS; t++);
pthread_join(guests[t], NULL);

这只是一个空循环。另外 - 第二行访问不在数组中的值,因为当时 t 等于 NUM_THREADS。应该是:

for(t=0;t<NUM_THREADS; t++)
pthread_join(guests[t], NULL);

或者更好:

for(t=0;t<NUM_THREADS; t++)
{
pthread_join(guests[t], NULL);
}

因此,一般来说,您的问题出在其他地方,并且您提出了错误的问题;-)

此外,这也是不正确的:

void *guest(void *threadid)
{
...

long tid;
tid = (long)threadid;

tid 将获取指针的值而不是它所指向的值。此外 - 您确定平台上的指针与 long 类型的长度相同吗?我怀疑。这也是问题所在:

long t;    
...
for(t=0; t<NUM_THREADS; t++)
{
...
pthread_create(&guests[t], NULL, guest, (void *)t);
}

您想要传递的是指向 t 的指针,但转换为 (void*),因此您应该使用:

pthread_create(&guests[t], NULL, guest, (void *)&t);

同样,您在 guest 例程中的 tid 分配应变为:

tid = *((long*)threadid);

关于c - 声明数组并在两种不同的方法中使用它 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20307202/

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