struct mystruct
{
int *p;//传递线程的头
int intel;//长度
int sum;//需要查找的值
int id;//编号
};
void lens(void *pd)
{
struct mystruct *ps = pd;
for (int *pi = ps->p; pi < ps->p + ps->intel; pi++)
{
if (*pi == ps->sum)
{
printf(“线程%d已经找到值%d,地址为%p\n”, ps->id,*pi,pi);
return;
}
}
printf(“线程%d查找结束,未找到!\n”, ps->id);
}
void main()
{
int sum = 0;
char array[100] = { 0 };
time_t ts;
unsigned int times = time(&ts);
srand(times);
for (int i = 0; i < 100; i++)
{
array[i] = rand() % 100;
}
for (int i = 0; i < 100; i++)
{
printf(“%3d”, array[i]);
if ((i + 1) % 10 == 0)
{
printf(“\n”);
}
}
scanf(“%d”, &sum);
struct mystruct xc[10];
for (int i = 0; i < 10; i++)
{
xc[i].p = array + 10 * i;
xc[i].intel = 10;
xc[i].id = i;
xc[i].sum = sum;
_beginthread(lens, 0, &xc[i]);
}
system(“pause”);
}
谁帮本人看看着程序错在哪里 printf(“线程%d已经找到值%d,地址为%p\n”, ps->id,*pi,pi); 输出的时候只有第8个线程找到,这是什么情况!
{
int *p;//传递线程的头
int intel;//长度
int sum;//需要查找的值
int id;//编号
};
void lens(void *pd)
{
struct mystruct *ps = pd;
for (int *pi = ps->p; pi < ps->p + ps->intel; pi++)
{
if (*pi == ps->sum)
{
printf(“线程%d已经找到值%d,地址为%p\n”, ps->id,*pi,pi);
return;
}
}
printf(“线程%d查找结束,未找到!\n”, ps->id);
}
void main()
{
int sum = 0;
char array[100] = { 0 };
time_t ts;
unsigned int times = time(&ts);
srand(times);
for (int i = 0; i < 100; i++)
{
array[i] = rand() % 100;
}
for (int i = 0; i < 100; i++)
{
printf(“%3d”, array[i]);
if ((i + 1) % 10 == 0)
{
printf(“\n”);
}
}
scanf(“%d”, &sum);
struct mystruct xc[10];
for (int i = 0; i < 10; i++)
{
xc[i].p = array + 10 * i;
xc[i].intel = 10;
xc[i].id = i;
xc[i].sum = sum;
_beginthread(lens, 0, &xc[i]);
}
system(“pause”);
}
谁帮本人看看着程序错在哪里 printf(“线程%d已经找到值%d,地址为%p\n”, ps->id,*pi,pi); 输出的时候只有第8个线程找到,这是什么情况!
解决方案
15
仔细看了一下,char array[100] = { 0 };这句替换成int array[100];,不然你的指针就乱了
30
#include<stdio.h> #include<stdlib.h> #include<time.h> #include<process.h> struct mystruct { int *p;//传递线程的头 int intel;//长度 int sum;//需要查找的值 int id;//编号 }; void lens(void *pd) { struct mystruct *ps = (struct mystruct *)pd; for (int *pi = ps->p; pi < ps->p + ps->intel; pi++) { if (*pi == ps->sum) { printf("线程%d已经找到值%d,地址为%p\n", ps->id, *pi, pi); return; } } printf("线程%d查找结束,未找到!\n", ps->id); } void main() { int sum = 0; int array[100] = { 0 }; time_t ts; unsigned int times = time(&ts); srand(times); for (int i = 0; i < 100; i++) { array[i] = rand() % 100; } for (int i = 0; i < 100; i++) { printf("%3d", array[i]); if ((i + 1) % 10 == 0) { printf("\n"); } } scanf("%d", &sum); struct mystruct xc[10]; for (int i = 0; i < 10; i++) { xc[i].p = array + 10 * i; xc[i].intel = 10; xc[i].id = i; xc[i].sum = sum; _beginthread(lens, 0, &xc[i]); } system("pause"); }