如果我把int p = 0,我发现; (p从不在代码中使用)代码将按照我的预期工作。
但是,如果我删除int p = 0;。当我在控制台中输入大约13个字符时(例如a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a
我很困惑这个int如何影响代码......?提前谢谢,这是代码。
#include <stdio.h>
#define NUMLINES 100 /*how many lines it can have in total */
#define BUFSIZE 5000
#define ASSIGNLEN 100
extern void copystring(char *, char *);
extern void readcontent(void);
char *lineptr[NUMLINES];
char* allocbuf(void);
static char alloc[BUFSIZ];
static char *allcp = alloc; /* allcp always point to next available address */
int p=0; /* THIS IS THE TROUBLE */
char *allocbuf(void);
char *allocbuf(void)
{
int n = ASSIGNLEN;
if(BUFSIZ+allcp-alloc<n){
printf("Buf full, cannot assign memory!\n");
return 0;
}
else{
allcp += ASSIGNLEN;
return allcp-ASSIGNLEN;
}
}
int main(int argc, const char * argv[]) {
readcontent();
int i=0;
while(lineptr[i]!=NULL){
printf("%s\n",lineptr[i]); /*if int p=0; is omitted, this line will throw EXC_BAD_ACCESS... */
i++;
}
return 0;
}
在另一个档案中:
#include "lineop.h"
extern char* allocbuf(void);
extern char* lineptr[];
void copystring(char *s, char *t);
void readcontent(void);
void readcontent(void)
{
char temp[100];
char *tempptr;
tempptr = temp;
int c,i;
i=c=0;
while((c=getchar())!='\n'){
if(c!=' ' && c!='\t' && c!='.'){
*tempptr = c;
tempptr++;
}
else{
*tempptr = '\0';
copystring((lineptr[i]=allocbuf()), temp);
i++;
tempptr=temp;
}
}
if(c=='\n'){
*tempptr = '\0';
copystring((lineptr[i]=allocbuf()), temp);
tempptr=temp;
i++;
}
}
void copystring(char *s, char *t) /* copy t to s*/
{
while(*t!='\0'){
*s=*t;
s++;
t++;
}
s++;
*s='\0';
}