如何将双指针的地址传递给另一个双指针

时间:2011-05-16 09:17:40

标签: c pointers double-pointer

如何将双指针的地址传递给另一个? 我有这个代码,只有当我设置注释行时它才能正常工作。为什么尺寸不同?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
    char *s1[]={"this","is","a","test"};
    char **s2;
    int i;
    s2=malloc(sizeof(s1)*sizeof(char *));
    s2=s1;
    for(i=0;i<sizeof(s2)/sizeof(char *);i++)//for(i=0;i<sizeof(s1)/sizeof(char *);i++)
        printf("%s",*(s2+i));
    return 0;
}

4 个答案:

答案 0 :(得分:2)

注释行使用sizeof(char*[4]),大概是未注释行上sizeof(char**)的四倍。

答案 1 :(得分:1)

使用sizeof运算符时,您将获得数组的大小(以字节为单位)。但是,当应用于指针时,您将获得指针的大小,而不是它指向的数据。

在C中,无法找到此信息,因此您必须手动管理此信息,例如通过使用size变量或(正如您已经完成)使用s1的大小(只有s1是一个数组才能工作。)

答案 2 :(得分:0)

sizeof(s1) ...给出总数。字节..

你认为反刍可能如下实施:

s2=malloc(sizeof(s1)*sizeof(char *));

s2[0] = malloc(sizeof(s1[0])*sizeof(char))
.
.
.
.
n so on

答案 3 :(得分:0)

sizeof(s1)给出外部数组中的总字节数,即指向字符串数组的四个指针的大小。在我的机器上,这给出了16个字节(每个指针是32位)。您对s1的声明与以下内容相同:

char *s1[4]={"this","is","a","test"};

您可以自己查看这些尺寸的结果:

printf("sizeof(char[4]) == %d\n", sizeof(char*[4])); // == 16
printf("sizeof(char**) == %d\n", sizeof(char**)); // == 4

由于s2是一个char **,从sizeof函数的角度看它实际上是一个char *,sizeof(s2)给出了一个char *的大小,它在我的机器上是4个字节。

如果要将s2指定给s1并将其打印出来,请尝试:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    char *s1[]={"this","is","a","teeeeeeeeeeest"};
    char **s2;

    s2 = s1;
    int numOfElementsInS1 = sizeof(s1)/sizeof(*s1);
    for(int i = 0; i < numOfElementsInS1; i++)
    {
        printf("s2[%d] = %s\n", i, s2[i]);
    }

    return 0;
}

......应该给出:

s2[0] = this
s2[1] = is
s2[2] = a
s2[3] = teeeeeeeeeeest

如果你的目标是复制s1的内容,那么你需要这样的东西:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    char *s1[]={"this","is","a","teeeeeeeeeeest"};
    char **s2;

    // Allocate memory for s2 and copy the array contents across
    int numOfElementsInS1 = sizeof(s1)/sizeof(*s1);
    s2 = (char**)malloc(sizeof(s1));
    for(int i = 0; i < numOfElementsInS1; i++)
    {
        size_t bytesInThisString = strlen(s1[i]) + 1; // + 1 for the string termination
        s2[i] = (char*)malloc(bytesInThisString);
        memcpy(s2[i], s1[i], bytesInThisString);
    }

    // Print out s2
    for(int i = 0; i < numOfElementsInS1; i++)
    {
        printf("s2[%d] = %s\n", i, s2[i]);
    }

    // Free up the memory
    for(int i = 0; i < numOfElementsInS1; i++)
    {
        free(s2[i]);
    }
    free(s2);

    return 0;
}