Array

Static array

  • declare array with length but without specific value, and check its length
int numbers[3];

#define LENGTH(x)  (sizeof(x) / sizeof((x)[0]))
int length = LENGTH(numbers); // length is 3

How do I determine the size of my array in C?

  • the static array should declare with the deterministic length.
int length = 20;
int numbers[length]; //error: variable-sized object may not be initialized

constexpr int LENGTH = 20;
int numbers[LENGTH]; // correct
  • declare array with specific value for elements
int numbers[10] = {0};
double doubles[10] = {0.0};
char chars[10] = {'\0'};
bool bools[10] = {false};
  • declare array with some specific value, others with default
int numbers[5] = {0, 1}; // [0, 1, 0, 0, 0]
double doubles[5] = {0.0, 0.1}; // [0.0, 0.1, 0.0, 0.0, 0.0]
char chars[5] = {'A', 'B'};
bool bools[5] = {false, true};
  • no needs to write length explitly
int numbers[] = {1, 2, 3, 4, 5, 6}; // it has 6 different default value

Dynamic array

  • declare without specific value
int *numbers = new int[length];
  • specify the value when declaration
  int length = 2;
  int *numbers = new int[length]{1, 2}; // {1, 2}

Create native array then ask Java to sort

  • Lib.kt
package com.practice

class Lib {

  external fun callNative()

  init {
    System.loadLibrary("native-lib")
  }
}
  • Sorter.kt
package com.practice

class Sorter {

  companion object {
    @JvmStatic
    fun sort(list: IntArray) {
      list.sort()
      list.take(10)
        .forEachIndexed { index, num -> println("$index: $num") }
    }
  }
}
  • MainActivity.kt
package com.hsy.anative

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.practice.Lib

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    Lib().callNative()
  }
}
  • native-lib.cpp
#include <jni.h>
#include <android/log.h>
#include <random>
#include <limits>

using namespace std;

constexpr auto TAG = "nativeCode";

#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)

jintArray cloneToJavaArray(JNIEnv *env, int nativeArray[], int length) {
  jintArray javaArray = env->NewIntArray(length);
  env->SetIntArrayRegion(javaArray, 0, length, nativeArray);
  return javaArray;
}

jclass findClass(JNIEnv *env, const char *name) {
  jclass cls = env->FindClass(name);
  if (cls == nullptr) {
    LOGE("class not found");
  }
  return cls;
}

jmethodID getStaticMethodId(JNIEnv *env, jclass cls, const char *methodName, const char *sig) {
  jmethodID result = env->GetStaticMethodID(cls, methodName, sig);
  if (result == nullptr) {
    LOGE("method id for %s(%s) not found.", methodName, sig);
  }
  return result;
}

void askJavaToSort(JNIEnv *env, int nativeArray[], int length) {
  // clone to Java array
  jintArray javaArray = cloneToJavaArray(env, nativeArray, length);

  // ask Java to sort array
  jclass cls = findClass(env, "com/practice/Sorter");
  env->CallStaticVoidMethod(cls, getStaticMethodId(env, cls, "sort", "([I)V"), javaArray);
  env->GetIntArrayRegion(javaArray, 0, length, nativeArray);

  // release
  env->DeleteLocalRef(cls);
  env->DeleteLocalRef(javaArray);
}

void printArray(int list[], int length) {
  for (int index = 0; index < length; index++) {
    LOGD("native #%d: %d", index, list[index]);
  }
}

void makeRandomNumbers(int nativeArray[], int length) {
  // init random num generator
  random_device rd;
  default_random_engine generator(rd());
  uniform_int_distribution<int> distribution(0, numeric_limits<int>::max());

  // make random number
  for (int index = 0; index < length; index++) {
    nativeArray[index] = distribution(generator);
  }
}

extern "C" JNIEXPORT void JNICALL Java_com_practice_Lib_callNative(JNIEnv *env, jobject) {
  constexpr int LENGTH = 20;
  int numbers[LENGTH] = {0};
  makeRandomNumbers(numbers, LENGTH);
  printArray(numbers, LENGTH);

  // ask Java to sort array
  askJavaToSort(env, numbers, LENGTH);
  printArray(numbers, LENGTH);
}

maximum value of int

Generating a uniform random integer in C++

C++11 內建亂數函式庫使用教學:隨機亂數產生器與機率分布

results matching ""

    No results matching ""