【问题标题】:How to iterate through an pointer that holds an array in C如何遍历保存C中数组的指针
【发布时间】: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]);

标签: c pointers pthreads


【解决方案1】:

你的意思是这样的吗:

#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;
}

?

几个细微差别:

  1. 您不需要任何线程

  2. 定义 char *word = "blahblah" 假定字符串是只读(又名 const)数据并且通常不可写(生成异常),这与 char word[] = "blah-blah" 在堆栈上本地分配数组不同。

  3. reverse_string() 函数中,我们交换,而不是不道德

【讨论】:

    猜你喜欢
    • 2021-05-29
    • 2013-03-22
    • 2018-06-30
    • 2012-11-06
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    相关资源
    最近更新 更多