鱼C论坛

 找回密码
 立即注册
查看: 2048|回复: 0

我怎么样来增添动态内存

[复制链接]
发表于 2012-1-27 22:49:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
/* Program 7.12 Arrays of Pointers to Strings */
#include <stdio.h>
#include <string.h>
#include<stdlib.h>
const size_t BUFFER_LEN = 512;              /* Size of input buffer      */
int main(void)
{
  char buffer[BUFFER_LEN];                  /* Store for strings         */
  char *pS[3] = { NULL };                   /* Array of string pointers  */
  char *pbuffer = buffer;                   /* Pointer to buffer         */
  size_t index = 0;
  int i=0;/* Available buffer position */
  printf("\nEnter 3 messages that total less than %u characters.", BUFFER_LEN-2);
  /* Read the strings from the keyboard */
  for(int i=0 ; i<3 ; i++)
  {
    printf("\nEnter %s message\n", i>0 ? "another" : "a" );

    pS[i] = &buffer[index]; //

  /* Save start of string      */
    /* Read up to the end of buffer if necessary */
    for( ; index<BUFFER_LEN ; index++)      /* If you read \n ... */
      if((*(pbuffer+index) = getchar()) == '\n')
        {
          *(pbuffer+index++) = '\0';/* ...substitute \0   */
          break;
//这里我可以动态分配内存 刚好需要index大小  pS[i]=(char*)malloc(strlen())这里我该怎么加刚好需要index大小也不浪费内存!最后我要释放内存在哪里增添!
   
   }
   

    /* Check for buffer capacity exceeded */
    if((index == BUFFER_LEN) && ((*(pbuffer+index-1) != '\0') || (i<2)))
    {
      printf("\nYou ran out of space in the buffer.");
      return 1;
    }

  }
  printf("\nThe strings you entered are:\n\n");
  for(int i = 0 ; i<3 ; i++)
    printf("%s\n", pS[i]);
  printf("The buffer has %d characters unused.\n",
                     BUFFER_LEN-index);
  return 0;
}




                               
登录/注册后可看大图
该贴已经同步到 空手套小白狼的微博
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-11 00:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表