關於動態記憶體分配與字串操縱的問題總結

來源:互聯網
上載者:User

關於動態記憶體分配與字串操縱的問題總結

#include <stdio.h> #include <stdlib.h>
#include <string.h>
#include <malloc.h>
 main()
{
  char *p;
  char *q;
  char *w;
  w=(char*)malloc(25*sizeof(char));
  if(w==NULL) exit(1);
  p=(char*)malloc(25*sizeof(char));
  if(p==NULL) exit(1);
  //q=(char*)malloc(10*sizeof(char));
  //if(q==NULL) exit(1);
 strcpy(p,"dongbeidaxue");
  q="chenyujie";
  printf("%s\n",q);
  printf("%s\n",p);
  strcat(p,q);
  printf("%s\n",p);
  free(w);
  w=NULL;
  free(p);
  p=NULL;
  //free(q);
  //q=NULL;

 }

程式很簡單,但是我卻調試了很長時間才搞懂;

首先要分清常量區和動態區;

q=“chenyujie”,其中chenyujie為常量,將常量的首地址賦給指標,賦給的是常量區首地址,這塊記憶體不允許修改的,對比p的操作,申請動態空間,利用strcpy函數操作,將內容移植到動態區,從而再利用strcat操作,成功。否則失敗。

總結就是動態記憶體的使用是基於堆的操作,是連續的可寫的,常量區是不可以改的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.