[英]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;
}
fgets
and store it in a temporary buffer (128 or 256 bytes large etc).fgets
获取输入并将其存储在临时缓冲区中(128 或 256 字节大等)。strlen
on the read string stored in this buffer to see how much to allocate.strlen
以查看要分配多少。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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.