简体   繁体   English

动态 memory 分配字符串并将此字符串放置在 char 数组中

[英]Dynamic memory allocation of string and placement of this string in a char array

I want to have an array of strings and the user to enter a string at a time.我想要一个字符串数组,用户一次输入一个字符串。 The program should either end if the the array is full or when the user skips an input (so the string would be equal to "\n". Problem is that I have to dynamically allocate memory for each of these strings and I cant find a way to do that efficiently.如果数组已满或用户跳过输入(因此字符串将等于“\n”),程序应该结束。问题是我必须为这些字符串中的每一个动态分配 memory,但我找不到有效地做到这一点的方法。

Excuse my English on this one but the array should be an array of pointers to char (for example char *pin[MAX]) This is my code:请原谅我的英文,但数组应该是指向 char 的指针数组(例如 char *pin[MAX])这是我的代码:

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#define MAX 5

int main()
{
   char *pin[MAX];

   char s[] = "";
   int n = 0;

   while(s != "\n"){

       printf("Enter a string: ");
       gets(s);

       pin[n] = malloc(sizeof(char)*strlen(s));
       strcpy(pin[n], s);

       n++;
       if(n = MAX - 1) break;
   }

   for(int i = 0; i < MAX; i++){
       printf("%s ", *pin[i]);
   }
   return 0;
}


  • Take input with fgets and store it in a temporary buffer (128 or 256 bytes large etc).使用fgets获取输入并将其存储在临时缓冲区中(128 或 256 字节大等)。
  • Call strlen on the read string stored in this buffer to see how much to allocate.对存储在此缓冲区中的读取字符串调用strlen以查看要分配多少。
  • Allocate memory with malloc for pointer pin[n] and strcpy the string there.为指针pin[n]分配 memory 和malloc并在那里对字符串进行strcpy

NOTE:笔记:

  • char *s; ... while(s != is nonsense since s has not been initialized. ... while(s !=是无意义的,因为s尚未初始化。
  • s != "\n" is nonsense since that's not how you compare strings in C. s != "\n"是无稽之谈,因为这不是您在 C 中比较字符串的方式。
  • pin[n] == &s; is nonsense because it's just random stuff typed out without the programmer knowing why.是胡说八道,因为它只是在程序员不知道为什么的情况下输入的随机内容。 Programming by trial & error doesn't work.通过反复试验编程是行不通的。
  • In general you need to study arrays and pointers before strings.一般来说,你需要研究 arrays 和字符串之前的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM