arrays - 为什么 const char *arr 的大小大于 const char arr[]?

标签 arrays c string pointers optimization

enter image description here我正在为 Microchip pic32 微 Controller 使用 xc32 编译器。

程序内存大小(用于启动、 vector 等)为 1656 字节。

#include <plib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>

//if I use const char array[] for string literal then the size of the program memory increased 
//equal to the string length(only 12 bytes)

//const char array[] = "Hello World"; //program mem size(1668 0x684) bytes

//but in this case size increased 28 bytes
//const char *array = "Hello World";  //program mem size(1684 0x694) bytes



int main {

    while(1);
}

为了优化目的:

哪个好(速度和大小)?

  1. #define STRLIT“ Hello World ”
  2. const char *strlit = "HELLO WORLD";
  3. const char arr[] = "HELLO WORLD"

最佳答案

一般MCU上的内存是这样存储的:What resides in the different memory types of a microcontroller?这意味着:

  • 字符串文字 "HELLO WORLD" 本身很可能存储在 .rodata 闪存 ROM 部分中。

  • 当您在文件范围执行 const char array[] = "Hello World"; 时,array 变量应该分配在 .rodata 中。因此不需要分配字符串文字,否则将意味着冗余分配。

  • 当您执行 const char *array 时,您声明了一个指针,它不是分配在闪存中,而是在 .data RAM 部分。所以这将意味着 RAM 和闪存消耗。请注意,此指针是可读/可写的 - 您可以将其分配到其他地方,但不能更改指向的内容。

    要在 flash ROM 中分配指针,需要执行 const char* const array

至于为什么你得到“28字节”的东西,我不知道。我没有用过这部分,但做了一个简短的研究here声称它可能具有冯诺依曼特性,从 C 程序员的角度来看,即使核心是哈佛。不确定归结为什么,但这很重要,因为哈佛架构可能需要执行一些支持开销代码来访问闪存 ROM 数据,这反过来会导致可执行文件的大小稍大。想知 Prop 体情况需要拆机。

关于arrays - 为什么 const char *arr 的大小大于 const char arr[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71016218/

相关文章:

ruby-on-rails - ruby/rails 根据字符串数组对记录数组进行排序

python - 一维数组的Numpy FFT(快速傅立叶变换)

c++ - 将 int 值写入字节数组

php - 从对象排序数组

c - 解析 HTTP header 的子集以识别主机 Web 地址

链接静态库时编译 CUDA 代码

java - Java 中的字符串和计数器数组

c - 字节反转整数的问题

c - C 中空格等于 '\0' 吗?我怎样才能避免混淆它们?

jquery - 如何使用 jQuery 删除链接文本中的第一个字符?