在通过sscanf更改字符串之一之前,我已经使这些功能正常工作。
即,如果我有一个在调用的函数中创建的char []名称,并将其初始化为字符串(例如“ fred”;),然后将其分配给传递的参数->参数在其父函数中更改。
但是,如果我尝试使用fgets-> sscanf的输入来更改字符串(NAME),然后将其分配给传递的数组,则父函数不会打印任何内容(“空白”)。
我试图找出字符数组与指针的情况。我以为我有它。我可以使用本地(初始化)字符串更改传递的String。但是,一旦我为本地字符串分配了一些“用户输入”,就不会正确更改参数字符串。
这是我的功能...
int enter_record(FILE *fp, const char *prompt[]) {
char *name[BUFFER] = {"wram"};
int score = 12; /* REPLACE : Put 0 or something ! */
fprintf(fp, "Enter_record()\n%s\n", *prompt); /* This is only here to use variables; so wil compile */
printf("Score: %d\n", score);
printf("Name:%s\n", *name);
get_name(prompt, name);
printf("Post-Change Name:%s\n", *name);
return 1;
}
int get_name(const char *prompt[], char *fullName[]) {
int n; /* The number of strings scanned */
char line[BUFFER]; /* The line that is scanned */
char firstString[BUFFER]; /* First scanned string */
char midString[BUFFER]; /* Second scanned string (',' ?) */
char lastString[BUFFER]; /* Last string scanned */
/* Function call validation */
printf("get_name()\n%s\n", *prompt);
if( !fgets(line, BUFFER, stdin) ) {
clearerr(stdin);
return 0; /* If *EOF* return FALSE */
}
if( !(n = sscanf(line, " %[a-zA-Z-] %[a-zA-Z-,] %[a-zA-Z-] %*s", firstString, midString, lastString)) ) {
printf("Wrong format!!!!\n");
}
printf("n:%d\n", n);
printf("firstString:%s\n", firstString);
*fullName= firstString;
return 1;
}
在下面,我将包括代码的其余部分(主菜单,菜单等)。
#include <stdio.h>
#define BUFFER 512
#define NAMELENGTH 14
int menu(const char *choices[], const char *prompt[]);
int enter_record(FILE *fp, const char *prompt[]);
int get_name(const char *prompt[], char *fullName[]);
int main(int argc, char *argv[]) {
FILE *ofp;
const char *menuOptions[] = {"Enter record", "Display records", "Quit", '\0'};
const char *prompt[2] = {"> "}; /* Prompt for user to enter input */
int menuResult;
/* Command line ARGS validation */
/*
VALIDATES main() is called correctly from console.
*/
/* Ensure program envoked correctly */
if(argc != 2) {
fprintf(stderr, "usage: %s [destination file]\n", argv[0]);
return 1; /* Incorrect-envocation error */
}
/* Open file for student records */
if( (ofp = fopen(argv[1], "wb+")) == 0) { /*If there's an error */
perror("fopen");
return 2; /* File-open error */
}
/*
///// END VALIDATION for main() call.
*/
printf("main()\n");
while(1) {
menuResult = menu(menuOptions, prompt);
switch(menuResult) {
case 0: /* Menu returned FALSE; */
return 0;
case 1: /* Enter Record; choice */
enter_record(ofp, prompt);
break;
default:
break;
}
}
return 0;
}
int menu(const char *choices[], const char *prompt[]) {
int i; /* Used to print menu "choice" "Number" */
char input[BUFFER]; /* The line scanned by fgets */
int choice = 0; /* What the user chooses */
int choiceLen = -1; /* Used to track how many elements in "choices[]"
This is used because (in my code) 'QUIT' is always last option
*/
/* Calculates # elements in *choices[] */
while (choices[++choiceLen] != NULL) {};
printf("\n");
for (i=0; choices[i] != '\0'; i++){
printf("%1d. %s\n", i+1, choices[i]);
}
while(1) {
printf("%s", *prompt);
if(!fgets(input, BUFFER, stdin)) {
clearerr(stdin);
return 0;
}
sscanf(input, "%d %*s", &choice);
if(choice == choiceLen) /* QUIT is always last option (choiceLen) */
return 0; /* Return QUIT */
else if ((choice > 0) && (choice < choiceLen)) /* 0 is invalid choice */
return choice;
}
return 0;
}
如果有人可以指出我哪里出了问题;
为什么用sscanf更改变量会改变父变量的影响方式?
我的困惑在于,它在“子字符串”被预先初始化时有效(例如char name [BUFFER] = {“ Bob”};),但在我用sscanf对其进行了更改之后却没有。
如果我的问题出在其他地方,也请告诉我。
任何方向的指针将不胜感激。
干杯。
最佳答案
问题在这里:
char line[BUFFER];
char firstString[BUFFER];
char midString[BUFFER];
char lastString[BUFFER];
这些是局部变量,这意味着字符数组在堆栈框架中。函数
get_name
完成后,将释放该内存。将指向该内存的指针暴露给外部世界(即函数enter_record
)是错误的。最简单的解决方案是在静态内存中分配字符串缓冲区:
static char line[BUFFER];
static char firstString[BUFFER];
static char midString[BUFFER];
static char lastString[BUFFER];
这种方法确实有一些缺点。
字符串缓冲区在程序的整个过程中都占用内存。
缓冲区大小必须为静态;它不能是在运行时确定的动态字符数。
替代方法是:
在
enter_record
而不是get_name
中定义字符串缓冲区(作为局部变量),这将相应地延长其寿命。让enter_record
在调用get_name
时将指针传递到缓冲区。使用
malloc
。我必须说我不赞成让get_name
分配内存,然后让enter_record
释放它;这会损害可维护性。