动态分配数组问题C.

时间:2016-12-21 15:18:01

标签: c arrays pointers dynamic-memory-allocation memcpy

要清楚,我的代码完美无缺。我担心的问题是我不确定我的数组分配类型。

我的任务很简单:我需要在动态分配的数组中执行一些操作。

然而,数值已在数组中给出。所以我需要在其中添加这些值。

保持我的矢量动态分配并避免以下情况:

func tableView(_ tableView: UITableView, cellForRowAt indexPath:  IndexPath) -> UITableViewCell {
   let cell:UITableViewCell!
   cell = tableView.dequeueReusableCell(withIdentifier: "language",for: indexPath)
   cell?.textLabel?.text = languageValues[indexPath.row]
}

 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
   if let cell = tableView.cellForRow(at: indexPath) {
       cell.accessoryType = .none
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
        cell.accessoryType = .checkmark     
 }

我试过这样做:

float *p;
 p = malloc(9 * sizeof(float));
* p=2;
* (p+1)=60;
* (p+2)=-23;
.
.
.
* (p+8)=9;

现在我不确定因为memcpy将静态分配的数组复制到我的float *p; p = malloc(9 * sizeof(float)); memcpy (p, (float[]) {2 ,60 ,-23, 55, 7, 9, -2.55, -66.9, 9}, 9 * sizeof(float)); 中。我的问题是:我的数组仍然是动态分配的?

编辑:我的问题是指第二段代码。

3 个答案:

答案 0 :(得分:6)

  

我的数组仍然是动态分配的吗?

float *p;
p = malloc(9 * sizeof(float));
memcpy ( p, (float[]){2,60,-23,55,7,9,-2.55,-66.9,9}, 9 * sizeof(float));

是。指针p的值保持不变。它仍然指向动态分配的内存 p[0],第一个元素现在的值为2.0f
p[1],下一个元素现在具有值60.0f等等。

一些编码建议:

int main(void) {
#define COUNT 9
  float *p = malloc(sizeof *p * COUNT);
  if (p) {
    memcpy(p, (float[COUNT] ) { 2, 60, -23, 55, 7, 9, -2.55f, -66.9f, 9 },
        sizeof *p * COUNT);
    //...
  }
  free(p);
  return 0;
}

答案 1 :(得分:3)

首先,你没有(y)数组,所有你都有一个指向特定大小内存的指针。

其次,如你所说,(强调我的

  

memcpy将静态分配的数组复制到我的p

所以,是的,指针仍然具有(或指向)动态分配的内存。

正如我们从C11看到的,章节§7.24.2.1

  

memcpy函数将n指向的对象中的s2个字符复制到   s1指向的对象。 [...]

因此,我们可以看到,对象本身不会被更改/替换,它只是被复制的内容。

答案 2 :(得分:0)

如果初始化值不变,则可以使用复合文字。但是,代码容易出错。如果您忘记了文字中的一个元素,您将访问数组越界。这会调用未定义的行为

改变三件事:

// use a macro for the length. In general don't use magic numbers!
#define ARRAY_LEN 9

// change the compound literal to:
... (static const float [ARRAY_LEN]){ ... }

这可以避免每次执行函数时复制文字。它还使文字不可变,因此编译器可以检查您是否尝试为其赋值。

注意:mempcy不会复制静态(盟友)分配的数组......"。这既不是你的数组的要求,也不是你使用静态对象的复合文字,而是自动的。

注意:如果函数执行的任何操作用于进一步处理,请始终检查可能遇到错误的函数的结果。 malloc可以在出错时返回空指针。妥善处理这种情况!