我正在尝试从数组中获取输入,输出和数据文件的名称,以进行进一步处理。但是,我收到一个奇怪的错误或问题。因此,我的程序未到达for循环。它甚至不打印for循环之前的语句。但是,我尝试使用调试器,程序可以正确地逐步打印。因此,当我运行它时,它不会打印,而当我逐步调试时,它会打印。那很奇怪!
char *method;
method=malloc(25);
method=NULL;
char *dataFileName;
char *inputMethod;
inputMethod=malloc(25);
inputMethod=NULL;
char *inputFileName;
char *outputMethod;
outputMethod=malloc(25);
outputMethod=NULL;
char *outputFileName;
char *commandArray[]={"if=q.txt","of=output.txt"};
char**args=(char**) malloc(sizeof(char*)*256);
args=commandArray;
int i;
printf("Before second for");
for(i=0;i<2;i++)
{
printf("I am here");
if(*args[i]=='d')
{
method=strtok_r(args[i],"=",&dataFileName);
printf("The method given is %s",method);
printf("Data File Name is %s",dataFileName);
}
else if(*args[i]=='o')
{
outputMethod=strtok_r(args[i],"=",&outputFileName);
printf("The output method given is %s",outputMethod);
printf("output File Name is %s",outputFileName);
}
else
{
inputMethod=strtok_r(args[i],"=",&inputFileName);
printf("The input method given is %s",inputMethod);
printf("Input File Name is %s",inputFileName);
}
}
if(method==NULL)
{
dataFileName=malloc(256);
printf("Please Enter A File Name");
scanf("%255s",dataFileName);
printf("%s",dataFileName);
}
if((inputMethod==NULL)||(outputMethod==NULL) )
{
char* array[]={"stdin","stdout"};
if(inputMethod==NULL)
inputMethod=array[0];
if(outputMethod==NULL)
outputMethod=array[1];
}
我正在C中使用Netbeans进行开发。上面的代码是在main内部编写的。谢谢!
最佳答案
我特意留下了先前的答案,因为特别是在c语言编程中,了解内存分配是微不足道的。正如我所见,您对此有很大的疑问。
但您几乎在每件事上都有问题。在我的实际答案中,我将尝试简化您如何使用strtok,拆分字符串并进行解析。我想这是您的代码的第二个主要问题。
代码 :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char commandArray[][256]={
"if=q.txt",
"of=output.txt"
};
char infile[256], outfile[256];
for(int i=0; i<2;i++){
char *ptr,*cmd;
cmd=commandArray[i];
ptr=NULL;
printf("parsing command '%s'\n",cmd);
cmd=strtok(cmd,"=");
ptr=strtok(NULL,"=");
if(!cmd){
printf("Error parsing the string '%s'\n",commandArray[i]);
exit(1);
}
if (strcmp(cmd,"if")==0){
strcpy(infile,ptr);
}
else if (strcmp(cmd,"of")==0){
strcpy(outfile,ptr);
}
else{
printf("unknow token '%s'\n",cmd);
exit(1);
}
}
printf(
"\n\n"
"input file: '%s'\n"
"output file: '%s'\n"
"\n\n",
infile,outfile);
return 0;
}
关于c - 指针读取不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33241819/