首页 > 解决方案 > 如何将常量字符串添加到给定位置的字符串数组中

问题描述

我想将像“d'Artagnan”这样的常量字符串添加到 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;
}

标签: arrayscstringpointers

解决方案


我会用另一种方式来做:

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它来展示如何分配字符串所需的确切内存)。


推荐阅读