首页 \ 问答 \ 如何将函数内的二维数组返回到C中的main(How do I return a 2D array inside a function to main in C)

如何将函数内的二维数组返回到C中的main(How do I return a 2D array inside a function to main in C)

我读了一个文本文件并将内容存储在一个名为H的2D数组中,我需要将这个2D数组以某种方式返回到main,所以我可以在那里使用它并将其传递给其他函数。 我不知道如何让返回工作,也许使用指针。 我将readTxtFile函数设置为void函数来测试文件读取是否正常工作(它确实如此)但我无法对函数外部的2D数组做任何事情。 我有两个函数getRows()和getCols(),我没有在这里显示,我可以,如果需要的话。

到目前为止,我的代码是:

int main(void){

    //  int *H;
    //  H = readTxtFile("H.txt");
    readTxtFile("H.txt");
    return 0;
}

void readTxtFile(char *filename){
    int rows, cols;
    FILE *fp = fopen(filename, "r");
    if (!fp){
        perror("can't open H.txt\n");
        //return EXIT_FAILURE;
    }
    rows = getRows(fp);
    cols = getCols(fp);
    int (*H)[cols] = malloc(sizeof(int[rows][cols]));
    if(!H){
        perror("fail malloc\n");
        exit(EXIT_FAILURE);
    }

    for(int r = 0; r < rows; ++r){
        for(int c = 0; c < cols; ++c){
            if(EOF==fscanf(fp, "%d", &H[r][c])){
                fprintf(stderr, "The data is insufficient.\n");
                free(H);
                exit(EXIT_FAILURE);
            }
        }
    }
    fclose(fp);

    // printH(rows,cols,H);
    //  return H;


}

这是文本文件的样子:

1 1 0 1 0 0
0 1 1 0 1 0
1 0 0 0 1 1
0 0 1 1 0 1
2 2 2 2 2 2

任何帮助,将不胜感激


I read a text file and store the contents in a 2D array called H inside a function, I need to return this 2D array to main somehow so I can use it there and pass it to other functions. I'm not sure how to get the return to work, maybe using pointers. I made the readTxtFile function into a void function to test if the file reading was working (it does) but I can't do anything with the 2D array outside the function. I have two functions getRows() and getCols() that I didn't show here, I can if needed though.

Heres my code so far:

int main(void){

    //  int *H;
    //  H = readTxtFile("H.txt");
    readTxtFile("H.txt");
    return 0;
}

void readTxtFile(char *filename){
    int rows, cols;
    FILE *fp = fopen(filename, "r");
    if (!fp){
        perror("can't open H.txt\n");
        //return EXIT_FAILURE;
    }
    rows = getRows(fp);
    cols = getCols(fp);
    int (*H)[cols] = malloc(sizeof(int[rows][cols]));
    if(!H){
        perror("fail malloc\n");
        exit(EXIT_FAILURE);
    }

    for(int r = 0; r < rows; ++r){
        for(int c = 0; c < cols; ++c){
            if(EOF==fscanf(fp, "%d", &H[r][c])){
                fprintf(stderr, "The data is insufficient.\n");
                free(H);
                exit(EXIT_FAILURE);
            }
        }
    }
    fclose(fp);

    // printH(rows,cols,H);
    //  return H;


}

This is what the text file looks like:

1 1 0 1 0 0
0 1 1 0 1 0
1 0 0 0 1 1
0 0 1 1 0 1
2 2 2 2 2 2

Any help would be appreciated


原文:https://stackoverflow.com/questions/40090326
更新时间:2022-12-27 17:12

最满意答案

您正在抓取键盘,这意味着所有键盘输入都将转到您的程序,没有其他窗口可以接收键盘输入。 这就是抓住键盘的重点。


You are grabbing the keyboard, that means that all keyboard input will go to your program, no other window can receive keyboard input. That's the point of grabbing the keyboard.

相关问答

更多
  • 您可以使用此代码隐藏软键盘 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 获取EditText的实例 EditText editText = (EditText) findViewById(R.id.edittext); 要防止Default SoftKeyboard出现在EditText中,请覆盖以下事件 //显示自定义键盘 edittext.setOnFoc ...
  • 您正在抓取键盘,这意味着所有键盘输入都将转到您的程序,没有其他窗口可以接收键盘输入。 这就是抓住键盘的重点。 You are grabbing the keyboard, that means that all keyboard input will go to your program, no other window can receive keyboard input. That's the point of grabbing the keyboard.
  • 你基本上添加一个 QLineEdit *lineEdit; 到你的fooLineEdit ,而这又是另一个QLineEdit 。 这在setupUi发生: lineEdit = new QLineEdit(fooLineEdit); 我认为这足以让事情变得fooLineEdit ( fooLineEdit的事件处理程序永远等待一个很可能发生在内部 QLineEdit内部的事件)。 尝试在不使用ui的情况下实现QLineEdit子类。 标题: class fooLineEdit : public QLin ...
  • 我创建了一个行为,在按下键的情况下我更新了绑定: public class KeysChangedBehavior : Behavior { protected override void OnAttached() { this.AssociatedObject.AddHandler(ComboBox.KeyDownEvent, new RoutedEventHandler(this.OnKeysCha ...
  • 问题是FocusManager.FocusedElement仅控制FocusScope的局部焦点。 由于Button不是它自己的FocusScope,它没有任何效果。 您需要调用Focus()方法,这需要您编写一些代码。 您可以执行明显的操作并编写事件处理程序,或者您可以执行非显而易见的操作并创建附加属性“MyFocusManager.ForceFocus”,当从false转换为true时,设置FocusManager.FocusedElement 。 这是通过PropertyChangedCallback ...
  • 好。 我解决了我的问题。 我从edittexts中删除android:textIsSelectable =“true” 。 有用 Ok. I solved my problem . I removed android:textIsSelectable="true" from edittexts . It worked
  • 我将创建更多轻量级对象,如System.Windows.Media.DrawingVisual对象,并在绘图上下文中绘制矩形。 这些将托管在充当ItemsControl的Framework元素中。 这篇伟大的文章描述了如何实现有效的ItemsControl: 编写更高效的ItemsControls I would create more lightweight objects such as System.Windows.Media.DrawingVisual objects and draw the re ...
  • 看起来可以在MouseUp事件中更改焦点。 我想如果你做得太早,就像在GotKeyboardFocus事件中一样,你会在listview处理事件并选择所选项目之前窃取焦点。
  • 在调整ListView大小后的onSizeChanged()中添加此行。 editText.requestFocus(); In onSizeChanged() after resizing the ListView add this line. editText.requestFocus();
  • 我前段时间考虑过同样的问题,没有提供简单的解决方案,所以我将may PC(我主要编程的地方)的布局改为en-US,并将我的笔记本电脑留在了de-DE(我来自德国) - 差不多一个星期后,我把我的电脑改成了de-DE,因为我很困惑。 i thought about the same question some time ago, haven't fount an easy solution and so i changed the layout of may PC (where i do mostly pro ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)