gpt4 book ai didi

java - 将 Java 代码翻译为 C

转载 作者:行者123 更新时间:2023-11-30 21:43:04 25 4
gpt4 key购买 nike

我是 C 语言新手,显然我在理解所有内存和指针方面遇到了一些问题。所以我有以下 Java 代码:

public class Question_10
{
public static void sortInt(int[] array)
{
int top = 0;
while (top < array.length - 1)
{
if (array[top] < array[top + 1])
{
top++;
}
else
{
int temp = array[top];
array[top] = array[top + 1];
array[top + 1] = temp;
if (top > 0)
{
top--;
}
}
System.out.println(top);
}
}

public static void main(String[] args)
{
int[] arr = {5, 6, 10, 1, 45, 3};

sortInt(arr);
System.out.println();
}

}

啊,我已经完成了以下操作:

#include <stdio.h>

void sortInt(int arrayInput[])
{
int top = 0;
int arrLen = sizeof(arrayInput)/(sizeof(int);
while(top < arrLen - 1)
{
if(arrayInput[top] < arrayInput[top+1])
{
top++;
}
else
{
int temp = arrayInput[top];
arrayInput[top] = arrayInput[top + 1];
arrayInput[top + 1] = temp;
if(top > 0)
{
top--;
}
}
printf("%i", top);
}
}
void main()
{

int array[] = {5, 6, 10, 1, 45, 3};
sortInt(array);
return 0;
}

当然我遇到了很多错误:

$ gcc Question10.c
Question10.c: In function `sortInt':
Question10.c:6: error: parse error before ';' token
Question10.c: At top level:
Question10.c:16: error: `top' undeclared here (not in a function)
Question10.c:16: warning: data definition has no type or storage class
Question10.c:17: error: `temp' undeclared here (not in a function)
Question10.c:17: warning: data definition has no type or storage class
Question10.c:18: error: parse error before "if"
Question10.c:23: error: parse error before string constant
Question10.c:23: error: conflicting types for 'printf'
Question10.c:23: note: a parameter list with an ellipsis can't match an empty parameter name list declaration
Question10.c:23: error: conflicting types for 'printf'
Question10.c:23: note: a parameter list with an ellipsis can't match an empty parameter name list declaration
Question10.c:23: warning: data definition has no type or storage class
Question10.c: In function `main':
Question10.c:30: warning: `return' with a value, in function returning void
Question10.c:27: warning: return type of 'main' is not `int'
Question10.c:31:2: warning: no newline at end of file
Question10.c: At top level:
Question10.c:16: error: storage size of `arrayInput' isn't known
Question10.c:17: error: storage size of `arrayInput' isn't known

也许你可以给我任何关于问题的建议,一些一般性的指导会很有帮助,因为我真的迷失在 C 语言中的这些“对象”事物中。

最佳答案

此行有语法错误:

int arrLen = sizeof(arrayInput)/(sizeof(int);

尝试使用:int arrLen = sizeof(arrayInput)/sizeof(int);

如果您从解决这个问题开始,那么您可能会解决您遇到的一些其他问题。如果没有,请一次服用一个。

我看到的另一个错误是您将 main 方法声明为 void main() 并调用 return 0;。根据 C 标准,main() 方法应返回 int,因此更改声明。

关于java - 将 Java 代码翻译为 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13924929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com