繁体   English   中英

C ++结构的指针数组

[英]C++ pointer array of structure

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>

struct telephone
{
    char name[10];
    char tno[9];
};

void main()
{ 
    telephone a[5];
    clrscr();
    telephone* p;
    p = a;
    strcpy(a[0].name, "Aditya"); // initializing the array
    strcpy(a[1].name, "Harsh");
    strcpy(a[2].name, "Kartik");
    strcpy(a[3].name, "Ayush");
    strcpy(a[4].name, "Shrey");
    strcpy(a[0].tno, "873629595");
    strcpy(a[1].tno, "834683565");
    strcpy(a[2].tno, "474835595");
    strcpy(a[3].tno, "143362465");
    strcpy(a[4].tno, "532453665");

    for (int i = 0; i < 5; i++)
    {  
        puts((p+i)->name);cout<< " ";   //command for output
        puts((p+i)->tno );cout<<endl;
    }
    getch();
}

在这段代码中,在输出时,我没有得到名称的输出。 我只会得到(p+0)->name输出,而不会得到其他任何东西,但是如果我不初始化电话号码,那么我会得到name的输出。

struct存储在连续的内存位置中 ,因此,当您分配tno变量时,尝试将大于其绑定大小的数据存储在其中,剩余的位将添加到下一个内存位置

在你的代码tno [9]所以它可以存储最多 9个字符 ,虽然你给它只有9个字符 ,但什么的strcpy做的是,它也增加了\\0到最后,它试图将其添加到tno [10]它不存在并且超出范围,并将其存储在其他内存位置 (可能是下一个数组的位置)中,这导致未定义的行为。

您只需要按以下方式更改结构定义:

struct telephone
{ 
   char name[10];
   char tno[10]; // if you intend to store 9 digit number
 }; 

请记住,如果您打算将x个字符存储在一个字符数组中 ,那么您的数组必须为x + 1 如果使用字符数组似乎很困难,也许可以使用std::string

电话号码至少应大一。 电话号码超出一个字节进入下一个数组,并将名称更改为“ \\ 0”

strcpy(a[0].tno ,"873629595" );

将[1] .name从

"Harsh\0"

进入

"\0arsh\0"

结构布局

+---+---+---+---+---+---+---+---+---+---+
| A | d | i | t | y | a | \0|   |   |   |
+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+
| 8 | 7 | 3 | 6 | 2 | 9 | 5 | 9 | 5 | 
+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+---+
| \0| a | r | s | h | \0|   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+
+---+---+---+---+---+---+---+---+---+
| 8 | 3 | 4 | 6 | 8 | 3 | 5 | 6 | 5 | 
+---+---+---+---+---+---+---+---+---+

电话号码都没有空终止符的空间,并且超出了其空间覆盖。 实际上这是下一个数组元素名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM