-
error in function
Code:
#include <stdio.h>
int main()
{
char * concatenate(const char * first, ...) {
char*cat = NULL;
const char *p;
va_list args;
size_t len =1;
va_start(args, first);
for(p = first; p; p = va_arg(args, const char*)){
char * n = realloc (cat, (len += strlen(p)));
if(!n){
while(p = va_arg(args, const char*));
va_end(args);
free(cat);
return 0;
}
strcat (cat = n,p);
}
va_end(args);
return cat;
}
}
I get the below error while compiling it.
Any idea what error is in the function concatenate?
main.c:23:36: error: expected expression before ‘const’
while(p = va_arg(args, const char*));
-
You cannot nest functions! "concatenate() MUST be defined outside of main(), then called inside main().
As written with this correction, you will need to #include:
Code:
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
Indent your code consistently.
Turn on your warnings and turn up to the highest level. I make no assumptions about the compiler you are using and possible IDE.
Then test the code, and make further corrections.
-
Looks like you are trying to mimic the asprintf() GNU's function:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
int asprintf ( char **p, char *fmt, ... )
{
int size;
va_list args;
va_start ( args, fmt );
size = vsnprintf ( NULL, 0, fmt, args );
va_end ( args );
if ( size >= 0 )
{
char *q;
q = malloc ( size + 1 );
if ( ! q )
return -1;
va_start ( args, fmt );
vsprintf ( q, fmt, args );
va_end ( args );
*p = q;
return size;
}
return -1;
}
-
I am just curious to know what error in the function concatenate() defined above?
The behavior of realloc() in first iteration of loop is undefined.
Insufficient space is allocated to cat to accomodate the trailing NUL character for each iteration except the first.
The behavior of strcat() in the first iteration of loop is undefined because n may point to a NULL ('\0') character.
Attempting to return zero (0) on error creates a pointer from integer without cast. is this illegal?