c - Xcode错误信息没有逻辑意义

  • 本文关键字:Xcode 错误 信息 c xcode
  • 更新时间 :
  • 英文 :


我应该生成一个程序,该程序创建一个线程,该线程生成0到1之间的随机数并打印生成的随机数。

我从Xcode收到的错误信息没有任何逻辑意义。我尝试了很多不同的方法,我可能只是忽略了它,但我不能看到任何可能的语法错误

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void printMsg(char* msg) {
int status = 0;
printf("%sn", msg);
pthread_exit(&status);
}
int main(int argc, char** argv) {
pthread_t thrdID;
int* status = (int*)malloc(sizeof(int));
printf("creating a new threadn");
pthread_create(&thrdID, NULL, (void*)printMsg, argv[1]);
printf("created thread %dn". thrdID);
pthread_join(thrdID, &status);
printf("Thread %d exited with status %dn", thrdID, *status);
return 0;
}

哦,我现在看到了,你用句号代替了逗号:

printf("created thread %dn". thrdID);

应该

printf("created thread %dn", thrdID);

在一些现已删除的注释中指出,代码中还有其他需要纠正的问题。

以下是关于如何处理这些问题的一些建议:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void printMsg(char* msg) {
// The stack of the thread will be destryed on exit
// so you need to allocate the status value (or do some
// rather dubious casting... this is cleaner).
int* status_pointer = malloc(sizeof(int));
printf("%sn", msg);
// For demonstration purposes set it to something other than 0.
*status_pointer = 123;
pthread_exit(status_pointer);
}
int main(int argc, char** argv) {
pthread_t thrdID;
void* status = NULL;
printf("creating a new threadn");
// You should not blindly pass argv[1] without checking it's valid.
// You can provide a default value like I did below, or error out.
char *msg = argc > 1 ? argv[1] : "This is a default message.";
pthread_create(&thrdID, NULL, (void*)printMsg, msg);
// thrdId is pointer so use the %p format specifier.
printf("created thread %pn", thrdID);
pthread_join(thrdID, &status);
// same issue with %p
printf("Thread %p exited with status %dn", thrdID, *(int*)status);
// don't forget to free what you allocated.
free(status);
return 0;
}

相关内容

  • 没有找到相关文章

最新更新