Improved pointer to an array in c language

Last post displayed the value "assigned to a pointer to an array of char", and the result was unintended. T. I got an answer a few minutes after I posted it. I didn't solve it myself. items / 2cafa1ce8eb8412f7a45 # comment-01851c37576e638f6e0e) was attached, so the display was correct. Thank you.

I will post the source code and results immediately.

Pointer to an array of ints

#include <stdio.h>

int main(void){
	int itmp[3] = {1, 2, 3};
	int (*p3tmp)[3];

	p3tmp = &itmp;
	printf("p3tmp[%d][%d][%d]\n", *p3tmp[0], *p3tmp[1], *p3tmp[2] );
	printf("p3tmp[%d][%d][%d]\n", *(p3tmp[0]), *(p3tmp[1]), *(p3tmp[2]) );
	printf("p3tmp[%d][%d][%d]\n", (*p3tmp)[0], (*p3tmp)[1], (*p3tmp)[2] );
	printf("p3tmp[%d][%d][%d]\n", p3tmp[0][0], p3tmp[0][1], p3tmp[0][2] );

	return 0;
}

スクリーンショット 2016-01-17 15.16.22.jpg

As pointed out, * p3tmp [0] and * (p3tmp [0]) have the same display contents. And after the correction, the same content as the substituted content was displayed ^ ^ If you set the comment to (* p3tmp) [x], the intended content will be displayed, and the display was successful.

Array of pointers

#include <stdio.h>

int main(void){
	char *ptmp[] = {
					"hello",
					"World",
					"hello World"
				};
	char **phoge;

	printf("ptmp[0]\t⇒\t[%s]\n", ptmp[0] );
	printf("ptmp[1]\t⇒\t[%s]\n", ptmp[1] );
	printf("ptmp[2]\t⇒\t[%s]\n", ptmp[2] );
	printf("-----------------------------\n");
	phoge = ptmp;
	printf("phoge[0]\t⇒\t[%s]\n", phoge[0] );
	printf("phoge[1]\t⇒\t[%s]\n", phoge[1] );
	printf("phoge[2]\t⇒\t[%s]\n", phoge[2] );
	printf("-----------------------------\n");

	return 0;
}

Store a number of character strings in an array and use it when outputting a message. I think this is an effective technique when the message is fixed.

I personally think that * ptmp [] is a multidimensional array, but even the declaration fails. Data type array name [number of elements 1] [number of elements 2]; I don't know the number of elements, so I declare it empty, so it fails ... Attempting to declare and assign a 2D array fails.

	char pptmp1[3][1];
	char *pptmp2[3];
	pptmp1 = ptmp;
	pptmp2 = ptmp;
error: array type 'char [3][1]' is not assignable
        pptmp1 = ptmp;
        ~~~~~~ ^
error: array type 'char *[3]' is not assignable
        pptmp2 = ptmp;
        ~~~~~~ ^

Unfortunately, I was able to declare char ** phoge; and assign it, so I judge that there is no problem.

Reference site

Digression

There seems to be a general-purpose pointer, but it will be later ^^

It will be a different site from next month. It is the trouble of temporary staff that the site changes ^ ^

Recommended Posts