我是 C 语言的新手。我知道线程是如何工作的,但我认为我仍然不明白指针如何与 char 数组一起工作,如何使用循环填充数组...
终端报错如下...
q2.c: In function ‘main’:
q2.c:18:22: warning: multi-character character constant [-Wmultichar]
q2.c:23:57: warning: multi-character character constant [-Wmultichar]
q2.c:23:40: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [enabled by default]
In file included from q2.c:4:0:
/usr/include/string.h:128:14: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
q2.c: In function ‘myfunc1’:
q2.c:61:23: error: invalid type argument of unary ‘*’ (have ‘int’)
ubuntu@ubuntu-VirtualBox:~/Desktop$ gcc q2.c -lpthread -o hell
q2.c: In function ‘main’:
q2.c:18:22: warning: multi-character character constant [-Wmultichar]
q2.c:23:57: warning: multi-character character constant [-Wmultichar]
q2.c:23:40: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [enabled by default]
In file included from q2.c:4:0:
/usr/include/string.h:128:14: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
q2.c: In function ‘myfunc1’:
q2.c:61:23: error: invalid type argument of unary ‘*’ (have ‘int’)
代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
void *myfunc1(void *ptr);
void *myfunc2(void *ptr);
pthread_mutex_t lock;
char name[10];
int id[10];
int i;
int main (int argc, char argv[])
{
memset(name, 'no' , sizeof(name));
memset(id, 0, sizeof(id));
for(i=0; i<10; i++)
{
strcpy(&name[i], 'name');
id[i] = i;
}
//name[10] = '\0';
pthread_t thrd1, thrd2;
int thret1, thret2;
char *msg1 = "First Thread";
char *msg2 = "Second Thread";
thret2 = pthread_create(&thrd2, NULL, myfunc2, (void *)msg2);
thret1 = pthread_create(&thrd1, NULL, myfunc1, (void *)msg1);
pthread_join(thrd1, NULL);
pthread_join(thrd2, NULL);
printf("\nthret1 = %d\n", thret1);
printf("\nthret2 = %d\n", thret2);
sleep(5);
printf("Parent Thread exiting...\n");
exit(1);
return 0;
}
void *myfunc1(void *ptr){
int i;
char *msg = (char *)ptr;
printf("\nMsg : %s\n", msg);
pthread_mutex_lock(&lock);
for(i=0; i<10; i++)
{
printf("\n %s ", *name[i]);
}
pthread_mutex_unlock(&lock);
}
void *myfunc2(void *ptr){
int i;
char *msg = (char *)ptr;
printf("Msg : %s\n", msg);
pthread_mutex_lock(&lock);
for(i=0; i<10; i++)
{
printf("\n%d ", id[i]);
}
pthread_mutex_unlock(&lock);
}
最佳答案
'
是指定字符,"
是指定字符串。在memset(name, 'no' , sizeof(name));
您正在尝试定义 c 中不允许的
'no'
。memset
用于设置一 block 内存的一个字符值。您可能需要memcpy
或strcpy
来初始化名称。char name[10];
定义了一个字符数组,但是如果你想定义一个字符串数组,你需要char name[10][NAME_LEN ];
而不是(对于字符长度的任何最大值)。这也应该修复strcpy
错误(不要使用 & 符号)。在
myfunc1
中,您正在取消引用一个字符。将其固定为 C 字符串的数组会有所帮助,但您无需取消引用它即可打印它。
关于c - 如何从不同的线程访问数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19214869/