English 中文(简体)
从java传来的c中打印数组:为什么不打印数组?
原标题:printing array in c passed from java : Why doesn t the array get printed?
  • 时间:2012-05-10 10:30:37
  •  标签:
  • java
  • c
  • arrays

以下java代码段调用c函数:

Java代码

 String s[] = new String[10];
    for(int i=0;i<10;i++) {
        s[i] = "s";
    }
    o.printArrayLength(s); // prints the array length from c code

C代码:

void Java_Package_CallMethodOfSuperClass_printArrayLength
    (JNIEnv *env, jobject obj, jobjectArray arr) {

jsize size = (*env)->GetArrayLength(env,arr);
printf("
");
printf("Size of array from C : ");
printf("%d",size);
jcharArray chrArr = (*env)->GetCharArrayElements(env,arr,NULL);
char Arr[11];
strcpy(Arr,chrArr);
int i = 0;
printf("Now printing the array declared in java from c :");
printf("SIZE SIZE SIZE SIZE : %d",size);
for(i=0;i<size;i++) {
    printf("Inside for loop !");
    printf("%s",Arr[i]);
}
     //jobjectArray obArr = (*env)->NewObjectArray(env,size,(*env)->FindClass(env,"[L"),NULL);
    //(*env)->SetObjectArrayElement(env,obArr,0,chrArr);
}

当发生上述情况时,我会看到以下输出:

Size of array from C : 10
Now printing the array declared in java from c :
SIZE SIZE SIZE SIZE : -549339085 // What the heck !

为什么我得到的大小值不同于10。值10在前一行打印。

接下来,如果我将for循环中的复选框保持为10,那么数组也不会打印出来。为什么会这样?相反,我得到了一个致命的错误。

问题回答

您应该注意编译器的警告,其中应该有几个警告。此代码已损坏。

您声明的是一个由11个字符组成的数组(<code>Arr</code>),但将其视为一个由10个字符串组成的数组。C中的字符串表示为指向char的指针。您的strcpy()很可能会覆盖Arr,从而导致size的值发生更改。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签