我正在试着写一个有结构和文件的程序。以下只是我代码的一部分(并不是整个程序)。我想要做的是:让用户编写他的命令。例如:删除John,例如。约翰·詹姆斯购买5000台ipad。
问题是,我想拆分命令,以便将其'args‘保存为struct元素。这就是我使用strtok的原因。但是我还面临着另一个问题,那就是谁把它们‘放’在结构上。对我来说,如何以一种安全的方式将'args‘传递给struct似乎很奇怪,因为我保存了一个二进制文件上的所有输入(来自用户),这些二进制文件可能会被重新打开和重写,所以我不能使用:
strcpy(catalog[0]->short_name, args[1]); 因为是时候将短名称保存在结构的第一个元素中了。但是如果文件被写入,那么会发生什么呢?第一个元素存在,所以如果我写..我会在上面写的吗?我该怎么办?提前感谢您的帮助!:D
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
char command[1500];
struct catalogue
{
char short_name[50];
char surname[50];
signed int amount;
char description[1000];
}*catalog[MAX];
int main ( int argc, char *argv[] )
{
int i,n;
char choice[3];
printf(">sort1: Print savings sorted by surname\n");
printf(">sort2: Print savings sorted by amount\n");
printf(">search+name:Print savings of each name searched\n");
printf(">delete+full_name+amount: Erase saving\n");
printf(">enter+full_name+amount+description: Enter saving \n");
printf(">quit: Update + EXIT program.\n");
printf("Choose your selection:\n>");
gets(command); //it save the whole command
/*in choice it;s saved only the first 2 letters(needed for menu choice again)*/
strncpy(choice,command,2);
choice[2]='\0';
char** args = (char**)malloc(strlen(command)*sizeof(char*));
memset(args, 0, sizeof(char*)*strlen(command));
char* temp = strtok(command, " \t");
for (n = 0; temp != NULL; ++n)
{
args[n] = strdup(temp);
temp = strtok(NULL, " \t");
printf(" %s ",args[n]);
}
strcpy(catalog[0]->short_name, args[1]); //segmentation fault
strcpy(catalog[0]->surname,args[2]);
catalog[0]->amount=atoi(args[3]); //atoi doesn't work
strcpy(catalog[0]->description,args[4]);
}因此,在运行程序后,我得到了一个分段故障...对于行:
strcpy(catalog[0]->short_name, args[1]); 有什么帮助吗?有什么想法吗?
发布于 2010-05-14 22:14:14
您有两个错误:
catalog[MAX]数组包含指向你的struct catalogue的MAX指针,但是它们都没有被初始化。解决这个问题的方法是要么不将它们声明为指针,要么根据需要将它们声明为变量,就像在catalog[0] = (struct catalogue *)malloc(sizeof(struct catalogue));args malloc中那样。首先,我不认为您打算创建一个长度等于命令字符串长度的字符串数组。这意味着如果您键入"sort1“,您将创建args[5]。这是无稽之谈,因为命令的长度与它应该有多少个参数无关。但是假设您真的想这样做,那么您将为数组创建空间,而不是为数组中的字符串创建空间。无论如何,你最终都会得到一个段错误(尽管你得到的是由于上面的#1 )。您需要在使用时为args中的每个元素分配空间。
代码可能如下所示:
for (n = 0; temp != NULL; ++n)
{
args[n] = (char *)malloc((strlen(temp) + 1) * sizeof(char));
strcpy(args[n], temp);
// and so on
}发布于 2010-05-14 21:17:55
for循环一次分配一个参数(args[n] = ...),但随后在每次传递时访问多个参数:*args[1]、args[2]等,这些参数在第一次传递时未初始化。
该警告是由另一个bug引起的。你不能像那样给数组赋值一个指针。请改用strcpy()。
发布于 2010-05-14 22:13:28
catalouge的数组是一个指针数组,而不是一个对象数组,但是这些指针没有初始化为任何值,因此出现了seg错误
尝试:
struct catalogue
{
char short_name[50];
char surname[50];
signed int amount;
char description[1000];
}catalog[MAX];
strcpy(catalog[0].short_name, args[1]); //segmentation fault
strcpy(catalog[0].surname,args[2]);
catalog[0].amount=atoi(args[3]); //atoi doesn't work
strcpy(catalog[0].description,args[4]); https://stackoverflow.com/questions/2834374
复制相似问题