我是C语言和编程的新手,我正试图将字符串传递到线程中,以便稍后对其进行操作。我尝试过使用数组char string[] = "word"
创建字符串并将其传递给线程——现在是指针char *word = "word"
,但没有成功。如何将字符串作为参数传递到线程中??
#include <stdio.h>
#include <stdlib.h> // exit calls
#include <pthread.h> // contains thread package
void *print_string_in_reverse_order(void *str)
{
char *string = (char *)str;
printf("%sn", *string); // this won't print anything
pthread_exit(NULL); // exit the thread
}
int main(int argc, char *argv[])
{
pthread_t threadID;
char *word = "word"; //should this be an array?
printf("In function main(): Creating a new threadn");
// create a new thread in the calling process
int status = pthread_create(&threadID, NULL, print_string_in_reverse_order, (void *)&word);
}
pthread_create(...., (void *)&word);
将地址传递给指针。&word
的类型为char**
,它是指向char
的指针。因此,您可以将其作为char**
获取,然后取消引用指针(并确保地址&word
对其他线程执行有效(,也可以按照您可能想要的方式直接传递word
-
printf("%sn", *string);
-*string
是char
,而不是char*
。CCD_ 14将指针扩展到类型为CCD_。启用编译器警告并监听它们-编译器应该警告此类错误。 -
在退出程序之前,您必须加入线程。因为
main
在pthread_create
之后立即退出,所以程序退出,其他线程也退出。因为第二个线程没有足够的cpu时间来执行printf
语句,所以不会打印出任何get(如果代码的其余部分有效的话(。.
所以你可能想:
void *print_string_in_reverse_order(void *str) {
char *string = str;
printf("%sn", string);
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t threadID;
const char *word = "word"; // string literals are immutable
printf("In function main(): Creating a new threadn");
int status = pthread_create(&threadID, NULL, print_string_in_reverse_order, word);
pthread_join(threadID, NULL);
}
您的问题是,当您使用&word
时,您正在将指向字符串指针的指针传递给您,您只需要在pthread_create
参数中使用word
。
这是因为当你申报时
const char* word = "my word";
"我的世界"的内存分配在只读全局内存中,然后word
成为堆栈上该内存的指针。请注意,即使不将word
声明为常量,也不能修改字符串。
const char word[] = "my word";
为"我的话"创建一个大数组。这通常不安全地传递到另一个线程,因为内存被删除,然后堆栈在函数结束时展开。
声明可修改字符串的最简单安全的方法是声明以下内容:
static char word[] = "my word";
这将保证"我的单词"在全局内存中,并且肯定可用,否则您将需要使用malloc
分配内存