查看此概念代码。它应该尊重 O(1) 要求
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char **strings;
char **strings2;
// init pointers with mnemonic memory addresses just for demo purposes
char *p1 = (char *) 0x01;
char *p2 = (char *) 0x02;
char *p3 = (char *) 0x03;
char *p4 = (char *) 0x04;
// define the size of pointe array
int limit = 3;
// malloc main
strings = malloc(sizeof(char *) * limit);
// fill up the pointer array
strings[0] = p1;
strings[1] = p2;
strings[2] = p3;
// debug - print out the initial state of pointers
printf("p1 %p p2 %p p3 %p p4 %p\n", p1, p2, p3, p4);
printf("original pointer array: %p %p %p\n", strings[0], strings[1], strings[2]);
// create another array of pointers and fill it up with shifted data
// and the new entry on the head
strings2 = malloc(sizeof(char *) * limit);
memcpy(strings2 + 1, strings, (limit - 1) * sizeof(char *));
strings2[0] = p4;
// free the original one and make it point to the modified array
free(strings);
strings = strings2;
printf("new pointer array: %p %p %p\n", strings[0], strings[1], strings[2]);
free(strings);
}
结果:
[root@mysrvr test]# ./a.out
p1 0x1 p2 0x2 p3 0x3 p4 0x4
original pointer array: 0x1 0x2 0x3
new pointer array: 0x4 0x1 0x2