0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C言語 配列越境で構造体を参照

Posted at

やりたいこと

配列も構造体も、プログラムを書きやすくするための仕組みに過ぎず、最終的にはメモリ上に連続した変数の集まりとして配置されます。
そこで、配列の直後に構造体を宣言し、配列の添字を範囲外まで越境させると構造体の中身を参照できるのではないかと考え、実験してみました。

メモリ上の位置関係

まずは配列と構造体のメモリ上での位置関係を把握する
構造体、配列の順番に宣言すると丁度配列の後に構造体が配置された。

test.c
struct S {int a,b,c;};

int main(){
  struct S s;
  int arr[3];

  arr[0]=44;
  arr[1]=44; 
  arr[2]=44;
  s.a=55;
  return 0;
}
test.s
main:
	push	{r7}
	sub	sp, sp, #28
	add	r7, sp, #0
	movs	r3, #44
	str	r3, [r7]
	movs	r3, #44
	str	r3, [r7, #4]
	movs	r3, #44
	str	r3, [r7, #8]
	movs	r3, #55
	str	r3, [r7, #12]
	movs	r3, #0
	mov	r0, r3
	adds	r7, r7, #28
	mov	sp, r7
	ldr	r7, [sp], #4
	bx	lr

配列経由で構造体の中身を参照する

test.c
#include<stdio.h>

struct S {int a,b,c;};

int main(){
  struct S s;
  int arr[3];

  arr[0]=44;
  arr[1]=44; 
  arr[2]=44;
  s.a=55;
  printf("arr[3]=%d", arr[3]);
  return 0;
}
testuser@CasaOS:~/test$ gcc test.c
testuser@CasaOS:~/test$ ./a.out 
arr[3]=55t
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?