【发布时间】:2020-03-01 22:45:41
【问题描述】:
C 新手,很难理解指针。我有一个任务要我将一个词传递给一个线程,然后反转这个词。我已经将这个词传递给函数中的线程,但我不知道如何迭代它。正确的语法是什么?
void *reverse_string(void *str)
{
// This function is called when the new thread is created
printf("In funciton reverse_string(). The value is %s\n", str);
char *p = (char *)str;
for(int i = 0; i < 7; i++) // loop not working for printing elements in array
{
p[i] = i;
printf("%s ....\n", p);
}
pthread_exit(NULL); // exit the thread
}
int main(int argc, char *argv[])
{
/* The main program creates a new thread and then exits. */
pthread_t threadID;
int status;
char * word = "SkAtIng";
//char *p = word;
printf("In function main(): Creating a new thread\n");
// create a new thread in the calling process
// a function name represents the address of the function
status = pthread_create(&threadID, NULL, reverse_string, (void*) word);
// After the new thread finish execution
printf("In function main(): The new thread ID = %d\n", threadID);
if (status != 0) {
printf("Oops. pthread create returned error code %d\n", &status);
exit(-1);
}
printf("\n");
exit(0);
}
【问题讨论】:
-
你能详细说明“不工作”吗?
p[i] = i;这当然不是在逆转任何事情。它用索引覆盖字符串字符。 “我不知道如何迭代它”。似乎您对for循环有基本的想法。逻辑不正确,但语法看起来或多或少很好。所以请澄清你的确切问题。 -
你和半小时前发this question的人是同一班吗? :)
-
char * word = "SkAtIng";这是一个不可修改的字符串文字。如果您希望线程能够写入它,请执行char word[] = "SkAtIng";。这将创建一个使用该字符串值初始化的(可写)数组。 -
另外,在主线程中需要一个
pthread_join。否则它会在创建线程后立即退出,并带走子线程,防止子线程做它的事情。 -
打印每个字符将
printf("%s ....\n", p);更改为printf("%c\n", p[i]);