字符串的动态内存分配和该字符串在char数组中的位置
我想有一系列字符串,用户一次输入字符串。如果数组已满,或者当用户跳过输入时,程序应结束(因此字符串等于“ \ n”。 问题是我必须为每个字符串中的每个字符串动态分配内存,而我找不到有效地做到这一点的方法。
请原谅我的英语,但阵列应该是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;
}
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.
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:
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
fgets
进行输入,然后将其存储在临时缓冲区(128或256个字节大等)中。strlen
在此缓冲区中存储的读取字符串上,以查看分配多少。malloc
将内存分配给指针pin [n]
和strcpy
在那里的字符串。注意:
char *s;
...while(s!=
是胡说八道,因为s
尚未初始化。s!= 因为这不是您比较C中的字符串的方式
fgets
and store it in a temporary buffer (128 or 256 bytes large etc).strlen
on the read string stored in this buffer to see how much to allocate.malloc
for pointerpin[n]
andstrcpy
the string there.NOTE:
char *s;
...while(s !=
is nonsense sinces
has not been initialized.s != "\n"
is nonsense since that's not how you compare strings in 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.