标签:
C风格字符串
如下示例代码,c文件,
#include <stdio.h> #include <stdlib.h> #include <string.h> void travel_str(){ char x = 0x21; //字符 ! while (x<=0x7e) { printf("%x is %c\n",x,x); x++; } } void test_c_style_str(){ //创建五个字符大小的内存空间,并返回首地址 char *start = malloc(5); *start = ‘L‘; *(start + 1) = ‘o‘; *(start + 2) = ‘v‘; *(start + 3) = ‘e‘; *(start + 4) = ‘\0‘; // 指针的下标运算 // start[0] = ‘L‘; // start[1] = ‘o‘; // start[2] = ‘v‘; // start[3] = ‘e‘; // start[4] = ‘\0‘; printf("%s has %zu characters\n",start,strlen(start)); printf("the third letter is %c\n",*(start + 2)); free(start); start = NULL; return; } //分配连续内存地址空间 void test_malloc(){ //分配3个float大小的内存地址空间,并返回首地址 float *start = malloc(3 * sizeof(float)); start[0] = 1.2; start[1] = 1.3; start[2] = 1.4; for (int i = 0; i<3; i++) { printf("the value is %f\n",start[i]); } free(start); start = NULL; } //字符串的字面量 void test_string_literal(){ const char *start = "Love"; //直接定义字符串字面量 while (*start!=‘\0‘) { printf("%x is %c\n",*start,*start); start++; } }
main文件,
#include <stdio.h> extern void travel_str(); extern void test_c_style_str(); extern void test_malloc(); extern void test_string_literal(); int main(int argc, const char * argv[]){ travel_str(); test_c_style_str(); test_malloc(); test_string_literal(); return 0; }
=====END=====
标签:
原文地址:http://my.oschina.net/xinxingegeya/blog/513326