【问题标题】:How to add a constant string into an array of strings at given position如何将常量字符串添加到给定位置的字符串数组中
【发布时间】:2021-08-29 13:42:37
【问题描述】:

我想将像“d'Artagnan”这样的 const 字符串添加到 8 个字符串的数组中 {“Duke of Buckingham”、“Porthos”、“Athos”、“Aramis”、“Planchet”、“Monsieur de Treville” , "Mousqueton", "Kitty"} 在字符串 "Aramis" 之后。但是当它运行时,“d'Artagnan”之后的字符串也是“d'Artagnan” 这是我的代码。

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

//function to add constant string
char addString(char *a[100], int *n, const char *s, int pos) {
for (int i = (*n); i > pos; i--) {
        a[i] = a[i-1];
    }
    strcpy(a[pos], s);  
    (*n)++;
}

int main() {
    int n;
    char *a[100], s1[10];
    strcpy(s1, "Aramis");

    // allocate array of strings and get input
    scanf ("%d", &n);
    for (int i = 0; i < n; ++i) {
        a[i] = (char*)malloc(100*sizeof(char));
    }
    for (int i = 0; i < n; ++i) {
    fflush(stdin);
    fgets(a[i], 100, stdin);
    strtok(a[i], "\n");
    }

    //add string "d'Artagnan" after string "Aramis" 
    for (int i = 0; i < n; ++i) {
        if (strcmp(a[i-1], s1) == 0) {
            addString(a, &n, "d'Artagnan", i);
        }
    }

    //Print output
    for (int i = 0; i < n; i++) {
        printf ("%s ", a[i]);
    }
    return 0;
}

【问题讨论】:

  • 这和C++有什么关系?
  • 你知道如何用 C 解决它吗?
  • 您传递给addString 的数组是什么样的?你怎么打电话给addString。乍一看,您似乎应该复制指针并为(或strdup)新字符串分配空间。
  • @NguyễnHà 这不是重点。如果这是纯 C 程序,请删除 C++ 标记。此外,it's wrong and idk why 的错误无效。更详细地描述失败的原因。
  • 请编辑您的问题,它属于哪里。 cmets 中的长段代码可读性不强。

标签: arrays c string pointers


【解决方案1】:

我会换一种方式:

typedef struct
{
    size_t size;
    char *names[];
}names_t;

names_t *addString(names_t *a, const char *s, size_t pos) 
{
    size_t newsize = a ? a -> size + 1 : 1;

    if(pos < newsize)
    {
        a = realloc(a, sizeof(*a) + newsize * sizeof(a -> names[0]));
        if(a)
        {
            a -> size = newsize;
            memmove(&a -> names[pos + 1], &a -> names[pos], sizeof(a -> names[0]) * (a -> size - pos - 1));
            if((a -> names[pos] = malloc(strlen(s) + 1)))
            {
                strcpy(a -> names[pos], s);
            }
            else
            {
                free(a);
                a = NULL;
            }
        }
    }
    else 
        a = NULL;
    return a;
}

当您添加字符串时,您的结构会增长。无需预先分配固定大小的数组。它还将为字符串的副本分配内存(您也可以使用 strdup 来说明如何分配字符串所需的确切内存)。

【讨论】:

    猜你喜欢
    • 2015-03-09
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 2023-01-19
    • 2020-10-25
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多