如何创建未知大小的字符串数组? [英] How to create an array of strings of unknown size?

查看:142
本文介绍了如何创建未知大小的字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何创建一个声明字符串数组"的C程序.在声明时其大小未知.这是到目前为止我得到的:

I'm trying to understand how can I create a C program that declares an "array of strings" whose size is unknown at the time of declaration. This is what I've got so far:

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

int main(void) {
  int n, i;
  char** words;

    printf("How many strings you want to input? \n");
    scanf("%d", &n);

  words = malloc(sizeof(char*) * n);

  for (i = 0; i < n; i++) {
    printf("Input your %d string: ", i + 1);
    scanf("%s", words[i]);
  }

  for (i = 0; i < n; i++) {
    printf("%s\n", words[i]);
  }

  return 0;
}

程序可以编译,但是出现 Segmentation fault 错误.

The program compiles, but I get a Segmentation fault error.

推荐答案

您只为指向字符串的指针分配了内存,而没有为字符串本身分配内存.尝试将字符串存储在未分配的内存中会导致未定义的行为.

You only allocated memory for the pointer to the strings, but not for the strings themselves. Attempting to store strings at non-allocated memory invokes undefined behavior.

指针只是指针.您不能在其中存储字符串.您需要为指针指向指向的位置保留内存.

The pointer are just pointer. You cannot store strings in them. You need to reserve memory for where the pointer should point to.

#define STR_SIZE 100              // max length of a string (incl. null terminator)

printf("How many strings you want to input? \n");
if (scanf("%d", &n) != 1)
{
    fputs("Error at input", stderr);
    // further error routine.
}

// allocate memory for the pointer to the strings.
words = malloc(sizeof(*words) * n);      
if (!words)
{
    // error routine if the memory allocation failed.
    perror("malloc"); 
    exit(EXIT_FAILURE);    
}

// allocate memory for the strings themselves.
for (int i = 0; i < n; i++)
{
     words[i] = malloc(sizeof(**words) * STR_SIZE);   
     if (!words[i])
     {
         // error routine if the memory allocation failed.
         perror("malloc"); 
         exit(EXIT_FAILURE); 
     }
}

旁注:

  • 如果分配时发生错误,请始终检查内存管理功能的返回!对于类似 scanf()的输入操作也是如此.

请注意,使用 sizeof(* words) sizeof(** words)而不是 sizeof(char *) sizeof(char)对于更改代码的情况更为安全.

Note that using sizeof(*words) and sizeof(**words) instead of sizeof(char*) and sizeof(char) is more safe for the case your code changes.

这篇关于如何创建未知大小的字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆