这是我到目前为止,当我编译它时,我收到此错误: lb54.c:在函数'funct1'中: lb54.c:38:2:警告:格式'%s'需要'char *'类型的参数,但参数2的类型为'int'[-Wformat =] 的printf( “%S \ n” 个,名称[I]); ^
当我将%s更改为%d时,它会起作用,但会显示一些随机数
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
void * funct1(void* arg);
void * funct2(void* arg);
void main(){
char name[10][20];
int *id = (int*)malloc(sizeof(int)*10);
int i,x=5;
for(i=0;i<10;i++){
strcpy(name[i],"name");
id[i] = i;
}
pthread_t threadid;
pthread_t threadname;
pthread_create(&threadid,NULL,funct2,(void *)id);
pthread_create(&threadname,NULL,funct1, &name);
sleep(5);
free(id);
printf("parent thread exiting\n");
}
void * funct1(void* arg){
int i;
char *name = (char *)arg;
for(i=0;i<10;i++){
printf("%s\n",name[i]);
}
}
void * funct2(void* arg){
int i;
int *id = (int *) arg;
for(i=0;i<10;i++){
printf("%d\n",id[i]);
}
}
答案 0 :(得分:0)
您已声明name
内的变量funct1
的类型为char *。当您使用[i]访问它时,它仅变为char,因此它不适合%s。
如果您确定name变量是一个字符串数组,请将其声明为char **name
或char *name[]
。
答案 1 :(得分:0)
感谢您的回答,我设法通过在每个名称条目的for循环中使用malloc来实现它(name [i] =(char *)malloc(20);)