在C中添加指向数组(指针)开头的指针

时间:2013-04-05 13:50:01

标签: c c-strings

我有一个char指针数组

char ** strings

长度为

limit

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

 {*str1, *str2, *str3}

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

 {*str4, *str1, *str2}

同时保持相同的尺寸

希望我足够清楚

谢谢

修改

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

4 个答案:

答案 0 :(得分:0)

如果你想在开头添加一个指针,你必须用1个元素增加其他指针的其他指针

您正在寻找的行为:在头部添加指针并删除尾部的指针(不执行其他操作):只能使用链接列表

答案 1 :(得分:0)

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

答案 2 :(得分:0)

可以使用链表概念完成。[首先插入]

步骤:

1)元素声明。

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

2)主要的头元素声明。

struct element *head;

3)将头部传递给插入函数

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;
}

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

答案 3 :(得分: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