c - 通过字符串的结构引用

标签 c arrays pointers structure

我正在尝试了解 C 结构的基础知识 敬请谅解 这是我的代码: 我在 Windows 7 上运行代码块

#include<stdio.h>
struct xx
{
    int a;
    char x[10];
};

int main()
{


struct xx *p;
p->a=77;

    p->x[10] = "hello";
        printf("\n %d",p->a);
                  printf("\n %s ",p->x);
return 0;
    }

在我尝试打印 p->x 的行中 程序崩溃 ! 第二个问题: 当我不初始化任何结构整数时,它们默认为零,这是真的吗? 如果在结构内部,则未初始化的 AND 字符串(字符星号)默认为空 第三个问题: 我尝试将行更改为

 p->x= "hello";

即使这样我也会出错! 我什至尝试过改变

 char tem[] = "hello";

  p->x[]= tem[];

我仍然收到错误

p->x= tem[];

这一行也给出了错误 甚至这个

 char *tmp = "hello";

  p->x= tem[];

连这个

 char *tmp = "hello";

  p->x[]= tem[];

即使这一行也是错误

 char *tmp = "hello";

  p->x[10]= tem[];

您可以关闭这个问题,但请澄清一下! 如何初始化结构体中的字符数组

最佳答案

您必须为 struct 分配内存,在尝试使用它之前,请使用 malloc() :

struct xx *p = NULL;
p = malloc(sizeof(struct xx));
if (!p) { 
    fprintf(stderr, "could not allocate memory for pointer p\n");
    exit(-1);
}
p->a = 77;
...
free(p); /* do this when you no longer need pointer p */

就访问x而言,最好复制字符串,例如:

#include <string.h>
...
if (strncpy(p->x, "blahblah", 4))
    fprintf(stdout, "p->x: %s\n", p->x); /* p->x: blah */
else {
    fprintf(stderr, "could not copy string to p->x\n");
    exit(-1);
}

尝试使用 strncpy() 在您可以的情况下,手动指定字符数可以帮助养成检查边界的习惯,从而有助于避免溢出。

例如,让我们尝试复制 const char *p->x ,它恰好比 p->x 长可容纳:

#include <assert.h>

#define MAX_LENGTH 10

struct xx {
    int a;
    char x[MAX_LENGTH];
};
...
const char *foo = "blahblahblah";
assert(strlen(foo) < MAX_LENGTH); /* code should fail here */
if (strncpy(p->x, foo, strlen(foo) + 1))
    ...

当您运行此命令时,assert()应跳闸:

Assertion failed: (strlen(foo) < MAX_LENGTH), function main, file test.c, line xyz.
Abort trap: 6

一次foo缩短为九个或更少的字符(记住,您需要第十个字符作为 \0 终止符!)代码应该正确运行。

所以使用strncpy()并检查你的界限!

关于c - 通过字符串的结构引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9139254/

相关文章:

c++ - 找到需要的头文件

c - 使用指针数学而不是数组索引

c - 关于 *argv[] 的指针

在 C 中使用 EOF 的条件

c - 制作链表时报错: Expected Expression Before 'struct' ,

c - 在 C 中,条件表达式的计算结果总是为 0 还是 1?

c++ - 指针传递和参数

javascript - 数组中的数组

javascript - 将php关联数组转换为javascript对象

按字母顺序将 2 个字符串组合到另一个字符串中