sizeof(s1)
外側の配列の合計バイト数、つまり文字列配列への4つのポインタのサイズを示します。私のマシンでは、これは16バイトになります(各ポインターは32ビットです)。s1の宣言は、次のことを行うのと同じです。
char *s1[4]={"this","is","a","test"};
これらのsizeofの結果を自分で確認できます。
printf("sizeof(char[4]) == %d\n", sizeof(char*[4])); // == 16
printf("sizeof(char**) == %d\n", sizeof(char**)); // == 4
はchar**であり、関数s2
の観点からは事実上char *であるため、私のマシンでは4バイトであるchar*のサイズを示します。sizeof
sizeof(s2)
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;
}