Reputation: 471
I'm making a function for retrieving a integer from a text file, according with its line and field number.
The code is shown below, the main issue is that I'm having problems with the functions arguments.
I'm having an error flag at the return value;
it says: that value
is undeclare
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* define function */
int getlinefieldint(const char FILENAME[], int TARGETLINE, int TARGETFIELD, int LINESIZE);
int main ()
{
static const char FILENAMEint[] = "resultdata1M";
int linea=1000;
int campo=2;
int tamanolinea=128;
int value;
value=getlinefieldint(FILENAMEint,linea,campo,tamanolinea);
printf("%d",value);
return 0;
}
/* declare function */
int getlinefieldint(const char FILENAME[], int TARGETLINE, int TARGETFIELD, int LINESIZE)
{
FILE *ARCHIVO;
ARCHIVO = fopen ( FILENAME, "r" );
int C,QUERY_GENE_NUM;
unsigned int NEWLINE_COUNT = 0;
while ( (C=fgetc(ARCHIVO)) != EOF )
{
if ( C == '\n' )
{
NEWLINE_COUNT++;
}
}
printf("La cantidad de genes a evaluar es: %d\n",QUERY_GENE_NUM);
rewind(ARCHIVO);
if (TARGETLINE <= NEWLINE_COUNT)
{
int j,value;
int stoplimitline;
char LINE[LINESIZE];
char *BUFFER;
char *TOKEN_SEPARA;
char *RETURNPTR;
BUFFER=(char *)malloc(24 * sizeof(char));
RETURNPTR=(char *)malloc(24 * sizeof(char));
while (stoplimitline < TARGETLINE)
{
fgets(LINE, sizeof LINE, ARCHIVO);
puts(LINE);
}
TOKEN_SEPARA = strtok(LINE, " ");
for (j=1;j<=TARGETFIELD;j++)
{
if(j!= TARGETFIELD)
{
BUFFER=strcpy(RETURNPTR,TOKEN_SEPARA);
puts(BUFFER);
TOKEN_SEPARA = strtok(NULL, " "); /* hacer que brinque el puntero al siguiente patron */
}
else
{
value=atoi(BUFFER);
}
}
}
return value ;
}
Upvotes: 0
Views: 72
Reputation: 7922
value
will cease to exist once
if (TARGETLINE <= NEWLINE_COUNT)
goes out of scope, because value
's declaration is within the if
statement.
The return
statement is outside of the if
statement, which means that value
will be attempted to be returned even though it does not exist.
Upvotes: 3
Reputation: 12563
Put the declaration of value
outside of if
block.
/* declare function */
int getlinefieldint(const char FILENAME[], int TARGETLINE, int TARGETFIELD, int LINESIZE)
{
FILE *ARCHIVO;
int value = 0; //or whatever default value it should have
Upvotes: 2
Reputation: 40804
Your problem lies here:
if (TARGETLINE <= NEWLINE_COUNT)
{
int j, value;
// ...
}
return value;
Note that in C (and many other languages), variables only "exist" in the code block they are declared in. So if you declare a variable inside a code block (such as an if
, while
or for
code block), then the variable will simply not exist when the program leaves this block of code.
The simple solution here is then to declare int value
before you enter the if
block:
int value;
if (TARGETLINE <= NEWLINE_COUNT)
{
int j;
// ...
}
return value;
Upvotes: 5