字符串的动态内存分配和该字符串在char数组中的位置

发布于 2025-01-21 11:13:17 字数 638 浏览 4 评论 0原文

我想有一系列字符串,用户一次输入字符串。如果数组已满,或者当用户跳过输入时,程序应结束(因此字符串等于“ \ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞慾 2025-01-28 11:13:17
  • 使用fgets进行输入,然后将其存储在临时缓冲区(128或256个字节大等)中。
  • 调用strlen在此缓冲区中存储的读取字符串上,以查看分配多少。
  • malloc将内存分配给指针pin [n]strcpy在那里的字符串。

注意:

  • char *s; ... while(s!=是胡说八道,因为s尚未初始化。
  • s!= 因为这不是您比较C中的字符串的方式
  • “ \ n” 是胡说八道, 为什么
  • Take input with fgets and store it in a temporary buffer (128 or 256 bytes large etc).
  • Call strlen on the read string stored in this buffer to see how much to allocate.
  • Allocate memory with malloc for pointer pin[n] and strcpy the string there.

NOTE:

  • char *s; ... while(s != is nonsense since s 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.
  • In general you need to study arrays and pointers before strings.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文