0

我有一个 char 指针数组

char ** strings

与长度

limit

我正在尝试将 char 指针添加到数组的开头,同时维护除最后一个之外的所有数组对象例如,如果我的数组有 3 个指针:

 {*str1, *str2, *str3}

我想添加*str4到开头,它看起来像这样:

 {*str4, *str1, *str2}

在保持相同大小的同时

希望我足够清楚

谢谢

编辑

我试图避免循环整个事情来移动指针。我正在为此寻找 O(1) 解决方案

4

4 回答 4

1

它可以用链表概念来完成。[首先插入)

脚步:

1)元素声明。

 struct element{
char *dataPtr;
struct element *next;
};

2)main中的头元素声明。

struct element *head;

3)将 head 传递给您的插入函数

struct element *new =(struct element *)malloc(sizeof(element));
insert(&head,new)

4)在插入功能中,

if (*head == NULL)
{
*head = new;
new ->Next = *head;
}
else
{
new->Next = *head;
*head = new;
}

在这些步骤中,您不需要遍历整个链表。

于 2013-04-05T14:06:22.227 回答
0

如果要在开头添加一个指针,则必须将其他指针从它们的位置增加 1 个元素

您正在寻找的行为:在头部添加一个指针并在尾部删除一个指针(没有其他操作):只能使用链表完成

于 2013-04-05T13:52:23.930 回答
0

如果您使用char **存储指向字符串的指针,则没有 O(1) 解决方案,只有明显的 O(n) 解决方案。虽然,您可能可以为 (n-1) 指针做一个 memcpy。

于 2013-04-05T13:54:18.567 回答
0

查看此概念代码。它应该尊重 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
于 2013-04-05T14:13:39.280 回答