【问题标题】:c programming, create dynamic array which stores pointers, strucc编程,创建存储指针的动态数组,struc
【发布时间】:2018-12-04 20:08:37
【问题描述】:

所以我的问题有点烦人。我必须创建一个名为 vector 的结构,它包含一个字符串 ~ 字符数组。供以后使用。到目前为止我写了什么:

vector.h
// forward declare structs and bring them from the tag namespace to the ordi$
typedef struct Vector Vector;

// actually define the structs
struct Vector {
    int SortPlace;
    char LineContent[100];
};

vector.c
// Initialize a vector to be empty.
// Pre: v != NULL
void Vector_ctor(Vector *v) {
    assert(v); // In case of no vector v
    (*v).SortPlace = 0;
    (*v).LineContent[100] = {""};
}

我的错误信息是:

vector.c: In function ‘Vector_ctor’:
vector.c:13:24: error: expected expression before ‘{’ token
  v->LineContent[100] = {""};

由于我是 C 编程新手,我有点迷路了。基本上我想创建一个没有内容的向量。

任何帮助将不胜感激。 问候

【问题讨论】:

  • (*v).foo ~> v->foo((*v).foo没有错,但是读起来很别扭)
  • 在vector.c: #include "vector.h"
  • in vector.h 将您的代码包含在 #ifndef VECTOR_H_INCLUDED 换行符 #define VECTOR_H_INCLUDED 和 #endif 中。见Why include guards?
  • 嗨 Swordfish,我已经包含了 vector.h 并附上了我的代码.. 没有在代码中显示它,因为我很确定它不是错误
  • (*v).LineContent[100] = {""}; ===> (*v).LineContent[0] = 0;

标签: c struct malloc


【解决方案1】:
 v->LineContent[100]

是一个char,您尝试将其初始化为一个数组/char *。


如果您已经有v,

memset(v, 0, sizeof(struct Vector));

将它归零(你必须#include <string.h>)。


写作

struct Vector new_vector = {0};

声明new_vector并将其所有内容初始化为\0。

【讨论】:

    【解决方案2】:

    您可以使用{} 指定数组中各个元素的值(在本例中为charts) or, as this is a special case, use""for the string (a null-terminated sequence ofcharts)来初始化它。你写的是两者的结合。

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      相关资源
      最近更新 更多