alloc complex data in c, and access in fortran

a.f90

bash 复制代码
program main
        use iso_c_binding
        implicit none
        type(c_ptr) :: ADD1
        type(c_ptr) :: c_ptr1
        external ADD1
        integer :: i
        complex :: z
        complex, pointer :: S(:)

        c_ptr1 = ADD1( )

        call c_f_pointer(c_ptr1, S, [10])
        print *, 'Array from C function: '
        do i = 1, 5
        print *, S(i)
        end do
        !        z = (1.0, 7.0)  ! 0 is the real part, 5.0 is the imaginary part
        !        print *, 'Complex number: ', z
end program

b.c

bash 复制代码
# include <stdlib.h>
# include <stdio.h>

float* add1_( )
{
        int n = 10; // size of the array
        float *arr = (float *)malloc(n * sizeof(float)); // allocate memory for n integers

        // Check if memory allocation was successful
        if (arr == NULL) {
                printf("Memory allocation failed\n");
                return NULL; // Return error code
        }
        // Initialize and print the array
        for (int i = 0; i < n; i++) {
                arr[i] = i * i; // Assign some values
                printf("%f ", arr[i]); // Print each element
        }
        printf("\n");
        return (float *) arr;
}

Makefile

bash 复制代码
all:
        gcc -c b.c -O0 -g
        gfortran a.f90 b.o -O0 -g -o a.out
相关推荐
tt5555555555554 分钟前
字符串与算法题详解:最长回文子串、IP 地址转换、字符串排序、蛇形矩阵与字符串加密
c++·算法·矩阵
扛麻袋的少年37 分钟前
7.Kotlin的日期类
开发语言·微信·kotlin
元亓亓亓39 分钟前
LeetCode热题100--101. 对称二叉树--简单
算法·leetcode·职场和发展
钢铁男儿1 小时前
Python 正则表达式实战:解析系统登录与进程信息
开发语言·python·正则表达式
不会学习?1 小时前
算法03 归并分治
算法
野生技术架构师2 小时前
2025年中高级后端开发Java岗八股文最新开源
java·开发语言
NuyoahC2 小时前
笔试——Day43
c++·算法·笔试
静若繁花_jingjing2 小时前
JVM常量池
java·开发语言·jvm
2301_821919922 小时前
决策树8.19
算法·决策树·机器学习
秋难降2 小时前
别再用暴力排序了!大小顶堆让「取极值」效率飙升至 O (log n)
python·算法·排序算法