Error message on return value assignment

时间:2016-04-25 09:14:10

标签: c

My code:

 #include <stdio.h>
 #include <stdlib.h>
 #include <stdarg.h>

 char * callMe(char *buf_test, const char *fmt, ...)
 {
    va_list ap;
    va_start(ap, fmt);
   vsnprintf(buf_test, sizeof(buf_test), fmt, ap);
   va_end(ap);
   return buf_test;
 }

 int main()
 { 
   char buf_t[100];
   int test_flag =1;
   buf_t = callMe(buf_t, "Test successful : %d", test_flag);
   printf("\n\n Result = %s", buf_t);
 }

Error:

error: array type 'char [100]' is not assignable
  buf_t = callMe(buf_t, "Test successful : %d", test_flag);
  ~~~~~ ^
1 error generated.

2 个答案:

答案 0 :(得分:1)

You can't assign to an array. You'll need to say something like this:

char *result = callMe(buf_t, "Test successful : %d", test_flag);
printf("\n\n Result = %s", result);

You've also got a problem with this line:

vsnprintf(buf_test, sizeof(buf_test), fmt, ap);

buf_test is delcared as a char* so applying sizeof to it will return the size of a pointer. Since you're getting "Test su` back it implies that the pointer size is 8 bytes. Although the variable points to an array the compiler has no way of inferring this.

What you need to so is pass the size of the buffer into the function:

char * callMe(char *buf_test, size_t size, const char *fmt, ...)
{
   va_list ap;
   va_start(ap, fmt);
   vsnprintf(buf_test, size, fmt, ap);
   va_end(ap);
   return buf_test;
}

and then pass the size when you make the call:

callMe(buf_t, sizeof(buf_t), "Test successful : %d", test_flag);

The compiler will be able to work out the size of the array here because it has access to the full definition of the variable.

答案 1 :(得分:-1)

As the error indicates, you cannot assing the result to an array. Instead, you can use a pointer by changing this line :

 buf_t = callMe(buf_t, "Test successful : %d", test_flag);

to :

 char *success;
 success = callMe(buf_t, "Test successful : %d", test_flag);

and therefore modify your print statement to :

printf("\n\n Result = %s", success);