我的程序输出令人困惑

时间:2016-08-04 11:14:40

标签: c arrays multidimensional-array

我的代码类似

enter code here

struct student
{
  int   ID;
   char name[20];
};

int l_search (char* list, int count, char* token)
{
__asm
{
     struct student
{
     int    ID;
     char   name[20];
};


   mov eax, 0; zero out the result
     mov esi, list; move the list pointer to ESI
    ; fill in your code here

    mov edi, token; move the token name pointer to edi
    mov ebx, 0; index of each construct in array
    mov edx, esi; set a pointer for each inside construct 
    add edx, 4; point to the first character in the string
compare:
    mov ecx, byte ptr[edx]; store the character to compare 
    cmp ecx, byte ptr[edi]; compare relative character 
    jne checkCase ;
nextletter:
    add edx, 1; to next character  
    add edi, 1;  to next charcter 
    cmp byte ptr[edi], 0; check the end of string 
    je found;
    jmp compare; continue compare 
checkCase:
     xor ecx, 24h; invert case 
     cmp ecx, byte ptr[edi] ; recompare the character with case insensitive
     jne nextConstruct; to next construct in the array 
     jmp nextletter; continue check next character 
nextConstruct: 
     add esi, 24; point to next construct 
     mov edx, esi; set the inside construct's character pointer 
     add edx, 4; point to first character 
     add ebx,1; to the next element in the array 
     cmp ebx, count; check arrays' boundary 
     jge finish;
     jmp compare ; continue compare 
found:
     mov eax, ebx; get the indext of the found name 
     add eax, 1;  get the ID 
    jmp nextConstruct;  continue checking next construct 

finish:


 }

}

所有3个值的输出都是相同的,任何人都可以告诉我原因。?

3 个答案:

答案 0 :(得分:1)

首先 - 正如其他人所指出的那样 - 你需要使用正确的格式说明符,并将这些值转换为指针。

现在为什么所有人都给出相同的价值。

这里x是一个数组。其元素的类型为unsigned int[3]。即x是一个数组 unsigned int[3]数组。

首先,x + 3 给出数组中第四个元素的地址。那就是 地址{10, 11, 12}。内存中此数组的地址将是其内存中第一个元素的地址。这是内存中10的地址。请注意,此值为int (*) [3],即address of an unsigned int[3] array

第二,* (x + 3) 相当于x [3],这是第四个元素,即unsigned int[3]。 它是数组{10, 11, 12}。该值指向的第一个元素 数组{10, 11, 12}。也就是说,此值指向10。请注意,此值为unsigned int[3]

第三个*(x+2) + 3:此处*(x + 2)相当于x[2] unsigned int[3],即{7, 8, 9}数组, 当您执行+ 3时,您将再次获得10的地址。请注意,此值为unsigned int[3]

因此,在所有三种情况下,您都会看到结果是内存中的相同地址,即存储10的地址 - 即使您在不同时间表示不同的内容;首先是unsigned int (*)[3],第二和第三是unsigned int[3]

答案 1 :(得分:0)

蒸馏未定义的行为:

printf("%u, %u, %u", x + 3, * (x + 3), * (x + 2) + 3);

所有额外参数必须为unsigned int,但2d为unsigned int (*)[3],3d为unsigned int *,第4个为unsigned int *

答案 2 :(得分:0)

你得到错误的值,因为你的指针算法错误了 x的类型为unsigned int[4][3],长度为4的数组,每个成员本身就是一个长度为3的数组。

那么x+3是什么?它是x中最后一位成员的地址(请记住x的成员是数组)。
因此*(x+3)本身就是一个数组。但是当你将它们作为函数参数传递时,数组会发生什么?他们腐烂成指针。所以你看到 数组中第一个元素的地址,被printf中错误的类型说明符所破坏。

好的,让我们来看看元素x[2][3]。它将是这种*(*(x+2)+3)的表达式,它完全等同于*(&x[0][0] + 2*3 + 3)