我是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);
}
答案 0 :(得分:2)
'
用于指定字符,"
指定字符串。在
memset(name, 'no' , sizeof(name));
您正在尝试定义c。
'no'
memset
用于设置一个内存块一个字符值。您可能需要memcpy
或strcpy
来初始化名称。
char name[10];
定义了一个字符数组,但是如果你想要定义一个字符串数组,则需要char name[10][NAME_LEN];
代替(对于字符长度的最大值)。这也应该解决strcpy
错误(不要使用&符号)。
在myfunc1
中,您正在取消引用某个角色。将其固定到c字符串的数组将有所帮助,但您不需要取消引用它来打印它。
答案 1 :(得分:0)
看起来你在字符串和字符常量之间很困惑。
char name [100]; char c;
字符串始终以“双引号”表示。 A(单个字符)用单引号括起来。所以,“stackoverflow”是一个字符串,'s','t','a','c','k'是字符。
此外,从字符串变量中,使用[]运算符提取单个字符,如下所示。请注意,我不使用'*'运算符。
char name[10] ;
char c;
strcpy (name,"stackoverflow");
printf ("name is %s",name);
print ("first character of name is %c", name[0]);