3

I've been trying to give out a matrix via logcat while using c++ and JNI. I'm totally new to this stuff and so after some research I tried it with the following code:

for(int i = 0; i<4; i++){
  for (int j = 0;j<4; j++){
    float v = Matrix[i][j];
    __android_log_write(ANDROID_LOG_INFO , "Matrix: ", (char*)&v);
  }
}

but this approach just gives me :

07-22 09:21:56.517  14487-14582/name.example I/Matrix:﹕ [ 07-22 09:21:56.517 14487:14582 I/Matrix:    ]

How can I show what's inside the matrix?

p7130
  • 63
  • 4
  • You're interpreting the `float`'s byte pattern as a char array. That doesn't work. Instead, use functions such as `std::to_string` or `sprintf` to convert the float to a string or character array. – hlt Jul 22 '15 at 07:56
  • `sprintf(somechar*,"%f",Matrix[i][j]` ? – p7130 Jul 22 '15 at 08:04
  • The first argument must be a pointer to `char`, so `sprintf(somechar, "%f", Matrix[i][j]);` with `char somechar[buffer_size];`. Make sure that your buffer is large enough, though. (if you can use the standard library and C++11, I would recommend `std::to_string(Matrix[i][j]).c_str()` instead). – hlt Jul 22 '15 at 08:09
  • It seems like you don't have C++11 (enabled, at least). Check out [this question](http://stackoverflow.com/questions/15616254/enable-c11-support-on-android) or use `sprintf` instead (or even `snprintf`, to make sure you don't get a buffer overflow). – hlt Jul 22 '15 at 08:23
  • Got it. Thank you so much :) – p7130 Jul 22 '15 at 08:28
  • I'll post it as an answer so that it is marked as solved and that others can learn from it – hlt Jul 22 '15 at 08:30
  • I'm not sure about your exact requirements, but if you can use `__android_log_print` instead, it already behaves like `sprintf`. – zenzelezz Jul 22 '15 at 08:33

1 Answers1

1

Your problem is in the following line of code:

__android_log_write(ANDROID_LOG_INFO , "Matrix: ", (char*)&v);

(char*)&v reinterprets the byte pattern of the float (v) as a C string, which doesn't work (and is also only occasionally allowed). Instead, to convert the float to a string, use sprintf or snprintf or, if possible, std::to_string (this requires C++11):

char str[buffer_size];
snprintf(str, buffer_size, "%f", Matrix[i][j]);
__android_log_write(ANDROID_LOG_INFO, "Matrix: ", str);

or

__android_log_write(ANDROID_LOG_INFO, "Matrix: ", std::to_string(Matrix[i][j]).c_str());

As pointed out in the comments, there is also __android_log_print, which integrates printf syntax already:

__android_log_print(ANDROID_LOG_INFO, "Matrix: ", "%f", Matrix[i][j]);
hlt
  • 6,219
  • 3
  • 23
  • 43