使用memcpy复制内存块时出现问题

时间:2016-09-06 16:52:48

标签: c

在我的下面的代码中,我将buffer作为使用malloc(r * c * sizeof(double*));创建的2D数组。我想使用buffertemp的前12个元素(即前4行)复制到第二个元素memcpy中。

double *buffer = malloc(10 * 3 * sizeof(double*));
double *temp = malloc(4 * 3 * sizeof(double*));

    for (int i = 0; i < 4; ++i) {
        memcpy(*(temp+ i*3), *(buffer + i*3), 3 * sizeof(double));
    }

我收到此错误:

memcpy(*(temp+ i*3), *(buffer + i*3), 3 * sizeof(double));
       ^~~~~~~~~~~~~~~~~~~~~~~~~~

有人可以告诉我为什么吗?

提前谢谢。

1 个答案:

答案 0 :(得分:2)

Traceback (most recent call last):
File "C:\Users\Adithya1\Documents\pywin and pyhook\Newfolder\pyHook\HookManager.py", line 351, in KeyboardSwitch
return func(event)
File "C:\Users\Adithya1\Documents\pywin and pyhook\New folder\systemdata.pyw", line 6, in OnKeyboardEvent
logging.basicConfig(filename=file_log, level=logging.DEBUG, format='%(message)s')
File "C:\Python27\lib\logging\__init__.py", line 1540, in basicConfig
hdlr = FileHandler(filename, mode)
File "C:\Python27\lib\logging\__init__.py", line 911, in __init__
StreamHandler.__init__(self, self._open())
File "C:\Python27\lib\logging\__init__.py", line 936, in _open
stream = open(self.baseFilename, self.mode)
IOError: [Errno 13] Permission denied: 'C:\\log.txt'

这是错误的,指向double *buffer = malloc(10 * 3 * sizeof(double*)); 的指针需要n double s的空间(不是指向double的n个指针)

更改为

double

double *buffer = malloc(10 * 3 * sizeof(double));

相同
  

我想复制缓冲区的前12个元素(即前4个元素   使用memcpy

进入第二个temp

使用:

temp
  

我收到此错误:

memcpy(temp, buffer, sizeof(double) * 12);
  

有人可以告诉我为什么吗?

> memcpy(*(temp+ i*3), *(buffer + i*3), 3 * sizeof(double)); > ^~~~~~~~~~~~~~~~~~~~~~~~~~ 想要一个指针(一个地址),但你要取消引用指针(因此传递一个像memcpy而不是地址的值)

你想要一个真正的2D阵列吗?

在这种情况下,您应该使用

3.14

看看defining a 2D array with malloc and modifying it

相关问题