更改结构数组中的值
Change values in a struct array
有人能给我解释一下吗,为什么我不能将值插入到结构数组中。
这是我的一段代码,可以帮助理解我想要完成的任务。
我想在一个由结构组成的数组中插入值,每当我尝试插入值时,它都会给我一个分段错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TAM_TABELA 10
#define PRIMO 7
#define MAX_NOME 50
typedef struct {
char nome[MAX_NOME];
int telemovel;
} pessoa;
void insert(pessoa *grupo[]) {
char nome[MAX_NOME];
printf("\nInsert name:\n");
scanf("%s", nome);
int lenght = strnlen(nome, MAX_NOME);
printf("\nInsert phone:\n");
scanf("%d", &tel);
for (i = 0; i < TAM_TABELA; i++) {
if (grupo[i] == NULL) {
grupo[i]->telemovel = tel;
strcpy(grupo[i]->nome, nome);
break;
}
}
if (i == TAM_TABELA)
printf("\nO valor não pode ser inserido!\n");
}
void main() {
int opt;
pessoa p;
pessoa grupo[TAM_TABELA] = {NULL};
insert(grupo);
}
- 您需要将
grupo
的地址传递给 insert()
函数。
int main(void) { }
是一个有效的 C main()
函数原型
size_t
是长度的有效数据类型,遍历数组
- 始终检查
scanf()
转换是否成功
- 不要使用
"%s"
,使用"%<WIDTH>s"
,避免
for( i = 0; i < TAM_TABELA; i++)
i
从未定义
- 函数
insert()
的参数应该是 pessoa ***grupo
,在 de-reference 中它稍后在你的函数中像 *grupo
- 使用
{}
初始化您的 char []
,它们存储在堆栈内存中
for (i = 0; i < TAM_TABELA; i++) {
if (grupo[i] == NULL) {
grupo[i]->telemovel = tel;
strcpy(grupo[i]->nome, nome);
break;
}
}
请注意您是如何检查 grupo[i]
是 NULL
然后您尝试访问该值的结构成员 NULL
.
您可能想要检查 grupo[i] != NULL
,这应该使成员访问安全。
有人能给我解释一下吗,为什么我不能将值插入到结构数组中。
这是我的一段代码,可以帮助理解我想要完成的任务。
我想在一个由结构组成的数组中插入值,每当我尝试插入值时,它都会给我一个分段错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TAM_TABELA 10
#define PRIMO 7
#define MAX_NOME 50
typedef struct {
char nome[MAX_NOME];
int telemovel;
} pessoa;
void insert(pessoa *grupo[]) {
char nome[MAX_NOME];
printf("\nInsert name:\n");
scanf("%s", nome);
int lenght = strnlen(nome, MAX_NOME);
printf("\nInsert phone:\n");
scanf("%d", &tel);
for (i = 0; i < TAM_TABELA; i++) {
if (grupo[i] == NULL) {
grupo[i]->telemovel = tel;
strcpy(grupo[i]->nome, nome);
break;
}
}
if (i == TAM_TABELA)
printf("\nO valor não pode ser inserido!\n");
}
void main() {
int opt;
pessoa p;
pessoa grupo[TAM_TABELA] = {NULL};
insert(grupo);
}
- 您需要将
grupo
的地址传递给insert()
函数。 int main(void) { }
是一个有效的 Cmain()
函数原型size_t
是长度的有效数据类型,遍历数组- 始终检查
scanf()
转换是否成功 - 不要使用
"%s"
,使用"%<WIDTH>s"
,避免 for( i = 0; i < TAM_TABELA; i++)
i
从未定义- 函数
insert()
的参数应该是pessoa ***grupo
,在 de-reference 中它稍后在你的函数中像*grupo
- 使用
{}
初始化您的char []
,它们存储在堆栈内存中
for (i = 0; i < TAM_TABELA; i++) { if (grupo[i] == NULL) { grupo[i]->telemovel = tel; strcpy(grupo[i]->nome, nome); break; } }
请注意您是如何检查 grupo[i]
是 NULL
然后您尝试访问该值的结构成员 NULL
.
您可能想要检查 grupo[i] != NULL
,这应该使成员访问安全。