c动态语言
函数声明的头文件在<stdlib.h>里
使用malloc函数为字符串分配内存 --》记得释放内存 free()
#include <stdio.h> #include <stdlib.h> #include <string.h> char *concat(const char *s1, const char *s2); int main(void) { char *p; p = concat("abc", "def"); printf("%s ", p); //abcdef return 0; } char *concat(const char *s1, const char *s2) { char *result; result = malloc(strlen(s1) + strlen(s2) + 1); if (result == NULL) { printf("Error: malloc failed in concat "); exit(EXIT_FAILURE); } strcpy(result, s1); strcat(result, s2); //放数据 return result; }
利用动态内存,字符串数组
#include <stdlib.h> #include <stdio.h> #include <string.h> #define MAX_REMIND 50 #define MSG_LEN 60 int read_line(char str[], int n); int main() { char *reminders[MAX_REMIND]; //定义字符串数组 char day_str[3], msg_str[MSG_LEN + 1]; // day_str是为了转换日期用,msg_str是存储字符串,存进数组用 int day, i, j, num_remind = 0; for (;;) { if (num_remind == MAX_REMIND) { printf("-- No space left -- "); break; } printf("Enter day and reminder: "); scanf("%2d", &day); if (day == 0) break; sprintf(day_str, "%2d", day); //把day转换成字符串 read_line(msg_str, MSG_LEN); //输入字符,变成字符串 /* for (i = 0; i < num_remind; i++) { // num_remind记录了有多少个字符串,这个步骤校验有问题,应该放到下面去 printf("ii: %d ",i); if (strcmp(day_str, reminders[i]) < 0) break; } for (j = num_remind; j < i; j++) reminders[j] = reminders[j - 1];*/ reminders[i] = malloc(2 + strlen(msg_str) + 1); //创建动态内存 if (reminders[i] == NULL) { printf("-- No space left -- "); break; } // printf("i: %d ", i); strcpy(reminders[i], day_str); strcat(reminders[i], msg_str); // 放数据 i++; num_remind++; } printf(" Day Reminder "); for (i = 0; i < num_remind; i++) { printf(" %s ", reminders[i]); } return 0; } int read_line(char str[], int n) { char ch; int i = 0; while ((ch = getchar()) != ' ') if (i < n) str[i++] = ch; str[i] = '