【问题标题】:How to add/remove a string in a dynamic array in c languagec语言如何在动态数组中添加/删除字符串
【发布时间】:2014-07-25 17:19:21
【问题描述】:

我有一个已定义的数组样本:

char *arguments[] = {"test-1","test-2","test-3"};

我正在尝试添加命令行给出的参数输入。我尝试了 strcpy 函数,并将它传递给数组元素,例如arguments[num+1] = argv[1] 但还是没有成功。

我知道这是一个非常简单的问题,但我不是经验丰富的程序员,我的所有经验都来自高级编程语言(PHP、Perl)。

我在网上找到的最接近的工作样本是C program to insert an element in an arrayC program to delete an element from an array。但并不是我要找的东西,他们正在使用 intigers 而不是我需要的角色。

我的目标是找到一种在动态数组中添加和删除字符串的方法,该数组可以根据脚本的进程进行增长和缩小。

感谢大家花时间和精力帮助我。

工作代码示例如下:

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

/* Set as minimum parameters 2 */
#define MIN_REQUIRED 2
#define MAX_CHARACTERS 46

/* Usage Instructions */
int help() {
  printf("Usage: test.c [-s <arg0>]\n");
  printf("\t-s: a string program name <arg0>\n");
  printf("\t-s: a string sample name <arg1>\n");
  return (1);
}

int main(int argc, char *argv[]) {

  if ( argc < MIN_REQUIRED ) {
    printf ("Please follow the instructions: not less than %i argument inputs\n",MIN_REQUIRED);
    return help();
  }
  else if ( argc > MIN_REQUIRED ) {
    printf ("Please follow the instructions: not more than %i argument inputs\n",MIN_REQUIRED);
    return help();
  }
  else {
    int size, realsize;
    char *input = NULL;

    char *arguments[] = {"test-1","test-2","test-3"};

    int num = sizeof(arguments) / sizeof(arguments[0]);

    printf("This is the number of elements before: %i\n",num);

    int i;
    for (i=0; i<num; i++) {
      printf("This is the arguments before: [%i]: %s\n",i,arguments[i]);
    }

    printf("This is the input argument: %s\n",argv[1]);
    printf("This is the array element: %i\n",num+1);

    input = (char *)malloc(MAX_CHARACTERS);
    if (input == NULL) {
      printf("malloc_in failled\n");
      exit(0);
    }

    memset ( input , '\0' , MAX_CHARACTERS);

    int length_before = strlen(input);
    printf("This is the length before: %i\n",length_before);
    strcpy(input , argv[1]);
    int length_after = strlen(input);
    printf("This is the length after: %i\n",length_after);

    //arguments[num+1] = input;

    strcpy(arguments[num+1],input);

    int num_2 = sizeof(arguments) / sizeof(arguments[0]);

    printf("This is the number of elements after: %i\n",num);

    for (i=0; i<num_2; i++) {
      printf("This is the arguments after [%i]: %s\n",i,arguments[i]);
    }

  } // End of else condition

  return 0;
} // Enf of int main ()

【问题讨论】:

  • 你不能那样使用数组。要么声明足够大的数组(例如char *arguments[MAX_ARGUMENTS],其中常量是一些合理的数字),要么在您知道有多少参数时动态分配它。

标签: c arrays string


【解决方案1】:
  1. “我的目标是找到一种在动态数组中添加和删除字符串的方法”:

    char *arguments[] = {...} 是静态分配的,所以不能作为“动态数组”。

  2. strcpy(arguments[num+1],input):

    当此数组只有 num 条目时,您无法访问 arguments[num+1]


建议修复-根据argc的值动态分配和初始化arguments

char* strings[] = {"test-1","test-2","test-3"};
int i, num = sizeof(strings) / sizeof(*strings);
char** arguments = malloc((num+argc-1)*sizeof(char*));
if (arguments == NULL)
    ; // Exit with a failure

for (i=0; i<num; i++)
{
    arguments[i] = malloc(strlen(strings[i])+1);
    if (arguments[i] == NULL)
        ; // Deallocate what's already been allocated, and exit with a failure
    strcpy(arguments[i],strings[i]);
}

for (i=0; i<argc-1; i++)
{
    arguments[num+i] = malloc(strlen(argv[i+1])+1);
    if (arguments[num+i] == NULL)
        ; // Deallocate what's already been allocated, and exit with a failure
    strcpy(arguments[num+i],argv[i+1]);
}

...

// Deallocate everything before ending the program

【讨论】:

  • 请注意,如果您要在失败后(或执行某些操作后)实际退出,则无需释放所有内容,因为退出会自动执行此操作。如果您要尝试继续尽管出现错误,那么您需要解除分配。
  • @ChrisDodd:对我来说听起来像是依赖于操作系统的东西,而不是标准定义的东西。
  • 谢谢,我想我知道如何解决这个小问题了。我会去的。
【解决方案2】:

C 中没有动态数组,arguments 具有静态大小,能够容纳 3 个元素,

strcpy(arguments[num+1],input);

只是未定义的行为,表达式arguments[num+1] 访问数组越界(两个元素在最后一个之后);不会发生神奇的重新分配,否则会发生某些事情。

一般来说,您有三种选择:

  1. 您有一个上限,即您希望能够在数组中存储多少项,并声明数组具有该大小。要么跟踪实际存储在其中的数字,要么添加一些标记值(需要额外的空间!)来指示结束。
  2. 您有一个上限,如果您要存储的项目数量碰巧超过了此限制,您将中止(返回错误指示器,告诉用户输入数据太大……)。
  3. 查找mallocreallocfree

【讨论】:

  • 好吧好吧我明白你的意思了。我认为我不需要指定数组的大小。我的印象是可以根据它所具有的元素增加或减少。那么在这种情况下,高级编程语言中的数组是如何指定的?感谢您花费时间和精力帮助我。
  • 不客气 :) 数组总是有一个固定的大小,没有办法调整它的大小。高级语言实际上并没有像 C 数组这样的东西。例如,Java 数组更像是指向 malloced(“new 等效”)内存的 C 指针(后者更灵活,例如,您可以在 C 中调整此类“Java 数组”的大小)。例如列表Python 或 Haskell 根本不是数组(在 O(1) 随机访问的意义上),它们是链表(你可以通过快速的网络搜索找到一堆关于 C 中链表实现的示例)。
  • 您可以自己编写数据结构,在必要时自动调整大小以获得类似于其他语言列表的行为。许多容器格式已经在一些库中实现,例如油嘴滑舌。在 C 项目开始时,您通常会花一些时间来规划要使用的内存策略。这是你应该熟悉的东西。也与您的问题有关:stackoverflow.com/a/24894968/1741125
猜你喜欢
  • 2014-12-18
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多