我是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("%s\n", *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 thread\n");
// create a new thread in the calling process
int status = pthread_create(&threadID, NULL, print_string_in_reverse_order, (void *)&word);
}
您的问题是使用时将指针传递给指向字符串的指针,&word
您只需要word
在pthread_create
参数中使用即可。
这是因为当您声明
const char* word = "my word";
“我的世界”的内存在只读全局内存中分配,word
然后a成为指向堆栈上该内存的指针。请注意,即使不声明word
为const,也无法修改字符串。
const char word[] = "my word";
创建一个大数组来表示“我的话”。通常,传递给另一个线程是不安全的,因为删除了内存,然后在函数末尾展开堆栈。
声明可修改字符串的最简单安全方法是声明以下内容:
static char word[] = "my word";
这将确保“我的话”位于全局内存中并且肯定可用,否则您将需要使用以下方式分配内存 malloc
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句