【问题标题】:Pushing characters in char array to index 0将 char 数组中的字符推送到索引 0
【发布时间】:2013-12-09 20:31:28
【问题描述】:

我正在尝试从 f 构建一个字符串,在空格处拆分并将其读入结构。 f 是我正在迭代的 char 数组。

然后我将 tmp 中的内容复制到 ra1.callsign 中,并基本上清空 tmp char 数组。

我想要做的是让 tmp 变量再次从索引 0 开始构建,这样当我第二次尝试 strcpy 时,tmp 中的所有字符都从索引 0 开始。 我现在拥有它的方式,当它尝试该行时: strcpy(ra1.location, tmp) 它不会复制任何内容,我认为这是因为那时 tmp 中的第一个字符直到某个时间才出现大批。

char c;
char tmp[1000];

for (i = 0; i < len; ++i) {
    c = f[i];

    if (c != ' ') {
        tmp[i] = c; //build string to be added
    }

    //add string to data structure
    if (c == ' ') {
        if (addTo == CALLSIGN) {
            strncpy(ra1.callsign, tmp, strlen(tmp));
            memset(tmp, '\0', strlen(tmp));
        }

        if (addTo == LOCATION) {
            strcpy(ra1.location, tmp);
        }

        ++addTo;
    }
}

希望这足够清楚,谢谢。

【问题讨论】:

  • 不,还不够清楚。
  • 这一行之后:memset(tmp, '\0', strlen(tmp));在我清空字符串的地方,循环继续再次构建字符串,最好是我想要一个函数,将数组中的所有字符推回索引 0 就在这一行之前:strcpy(ra1.location, tmp);
  • memmove() 会按照你的要求做,假设我有一个正确的祈祷。它可用于将子字符串的位置移动到另一个位置,覆盖已经存在的字符。它对源内存没有任何作用,除非有重叠,它可以正确处理。源总是覆盖目标。

标签: c arrays structure


【解决方案1】:

你在代码中遗漏了很多细节,我做了一些假设。

因此,使用我所做的假设(您可以在下面的代码中看到),我相信这将完成您想要完成的任务。有很多更简单、更简洁的方法可以做到这一点,但我希望您能清楚地了解它如何与您的代码一起使用。

我基本上在需要的地方添加了一个终止空字符,以便strlen() 函数可以正常工作,并使用了一个名为cur_size 的额外变量,它可以用作基于当前索引i 的偏移量。

#include <string.h>
#include <stdio.h>

#define CALLSIGN    3U
#define LOCATION    5U

#define ARRAY_SIZE   50U

typedef struct
{
    char callsign[ARRAY_SIZE];
    char location[ARRAY_SIZE];
} MyStruct;

MyStruct ra1 = { .callsign = {0}, .location = {0} };
char f[] = "This is my character array. Let's see what happens.";

int main (void)
{
    char c;
    char tmp[ARRAY_SIZE];
    unsigned char addTo = 0;
    unsigned char i;
    unsigned char cur_size = 0;

    for(i = 0; i < sizeof(f); ++i)
    {
        c = f[i];
        if(c != ' ')
        {
            tmp[i - cur_size] = c; //build string to be added
        }

        //add string to data structure
        if(c == ' ')
        {
            tmp[i - cur_size] = '\0';  /* YOU NEED THIS FOR strlen(tmp) to work */
            cur_size = i + 1;
            if(addTo == CALLSIGN)
            {
                strncpy(ra1.callsign, tmp, strlen(tmp));
                //memset(tmp, '\0', strlen(tmp));
            }
            else if (addTo == LOCATION)
            {
                strncpy(ra1.location, tmp, strlen(tmp));
            }

            ++addTo;
        }
    }

    for (i = 0; i < ARRAY_SIZE; i++)
    {
        printf("%c", ra1.callsign[i]);
    }
    printf("\r\n");

    for (i = 0; i < ARRAY_SIZE; i++)
    {
        printf("%c", ra1.location[i]);
    }
    printf("\r\n");

    return 0;
}

【讨论】:

    猜你喜欢
    • 2013-08-07
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 2021-09-14
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多