C编程中的字符串分配

时间:2015-07-03 04:31:48

标签: c

我是C的新手。为了存储字符串文字,我看到了两种方式,如下所示

    char s[]="Mohan";
    char *ptr="Mohan";

那么,这两者之间有什么区别。以及如何为这两个语句分配内存。

提前致谢...

4 个答案:

答案 0 :(得分:5)

在第一种情况下......

char s[] = "Mohan";

... s变量是一个字符数组。但是,第二种情况是这样的:

char s[] = "Mohan";
char *ptr = s;

实际上在某处有相同的字符数组,但除此之外,你还有一个指向该数组的指针变量。

答案 1 :(得分:1)

两者之间的区别在于char s[]="Mohan";存储在进程内存布局的读写区域中。

char *ptr="Mohan";字符串文字Mohan存储在只读区域。

表示您可以将字符指针指向任何其他字符串文字但不能编辑字符串。

#include <stdio.h>

int main(void)
{
    char a[] = "Stack";  //Here a is an array of characters
    char *p = "overflow"; // p is a pointer to char

    a[0] = 's';
    printf("%s\n", a); //Output is "stack"
    // *p = 'O'; This will cause segmentation fault as you are writing to a read
    // only memory 
    p = a;
    *p = 'O';
    printf("%s\n", a); //Output is "Otack"

    return 0;
}

答案 2 :(得分:1)

char s[]="MOHAN";

在此字符串中声明为字符数组,并像其他类型的数组一样存储。字符串将存储在读/写区域。这里程序员不需要知道它的大小,因为它将由初始化数据确定。     这也可以写成

char s[6]="MOHAN";

记住最后一个数组'\ 0'被存储。

char *ptr="MOHAN";

字符串值直接分配给指针并存储在共享只读位置,但指针存储在读/写存储器中。因此,只有在我们不必在程序的后期更改或修改字符串时才应使用此类。

答案 3 :(得分:0)

为此,

char s [] =&#34; Mohan&#34 ;;

  app.directive('modal', function($log) {
  return {
    restrict: 'E',
    templateUrl: 'modalTmpl',
    link: function(scope, element, attrs) { 
      self.element = element;
      scope.close = function() {
        $log.info('close!');
        var modal = self.element.find('.modal');
        //debugger;
        modal.removeClass('show');
      }

    },
    controller: function($scope, $attrs) {

    }
  };


var ModalDemoCtrl = function ($scope, $log) {

  $scope.items = ['item1', 'item2', 'item3'];

  $scope.open = function () {

  };
};

但在这种情况下,

char * s =&#34; Mohan&#34 ;;

内存未在读写区域中分配。内存分配在堆内存中的只读存储区中。    堆内存包含两部分。读写存储区和只读存储区。