[英]How to iterate through an pointer that holds an array in C
New to C and having a hard time understanding pointers.刚接触 C 并且很难理解指针。 I have an assignment that wants me to pass a word to a thread and then reverse the word.
我有一项作业要我将一个词传递给一个线程,然后反转这个词。 I've passed the word to the thread on into the function but I don't know how to iterate through it.
我已经将这个词传递给线程到函数中,但我不知道如何遍历它。 What is the proper syntax?
什么是正确的语法?
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);
}
do you mean something like this:你的意思是这样的:
#include <stdio.h>
#include <string.h>
void reverse_string(char *str)
{
int len = strlen(str) - 1, i;
if (len <= 0)
return;
for (i = 0; i < len / 2; i++) {
char tmp = str[i];
str[i] = str[len - i];
str[len - i] = tmp;
}
}
int main()
{
char word[] = "SkAtIng";
printf("original word: %s\n", word);
reverse_string(word);
printf("reversed word: %s\n", word);
return 0;
}
? ?
Couple of nuances:几个细微差别:
You don't need any threads你不需要任何线程
Defining char *word = "blahblah"
assumes the string is read-only (aka const) data and normally is not writable (generating exception), unlike that char word[] = "blah-blah"
allocates the array locally on the stack.定义
char *word = "blahblah"
假设字符串是只读(又名 const)数据并且通常不可写(产生异常),不像char word[] = "blah-blah"
在堆栈上本地分配数组。
In reverse_string()
finction we exchange values , not indecies在
reverse_string()
函数中,我们交换值,而不是 indecies
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.