arrays - 如何将常量字符串添加到给定位置的字符串数组中
问题描述
我想将像“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;
}
解决方案
我会用另一种方式来做:
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
它来展示如何分配字符串所需的确切内存)。
推荐阅读
- javascript - Nodejs-Sequelize 插入连接表多对多
- python - 有没有办法在 Celery 中设置 acks_late 配置?
- python - for循环中的Tkinter GUI
- angular - Angular TypeError:无法读取 null 的属性“必需”
- javascript - 为什么元素没有在 JavaScript 中获得过渡?
- android - 在recyclerview中使用多个本地图像资源的有效方法
- android - 如何使用 react-native-ble-plx 以编程方式配对蓝牙设备而无需用户交互?
- emacs - 我在哪里可以找到 Emacs 中的 use-package 依赖?
- npm - 如果文件夹已经存在,Gulp imagemin 跳过文件夹创建
- spring - Kotlin Failsafe 新参数