【问题标题】:Char array objective C [duplicate]Char数组目标C [重复]
【发布时间】:2016-06-26 13:35:54
【问题描述】:

我在使用 char 数组时遇到问题。 我的想法是使用scanf 将输入存储在char 数组中,然后将该数组的内容存储在struct 中。

下面的代码可能更容易理解:

struct ListaCategoria {
    int ident;
    char data[MAX];
    struct ListaCategoria* next;
};

struct ListaCategoria* headCat;

void inserirCat(){
    int x;
    char arr[MAX];
    printf("Identificacao : ");
    scanf("%d", &x);
    printf("Designacao : ");
    scanf("%c[^\n]", &arr);
    struct ListaCategoria* temp = (struct ListaCategoria*) malloc(sizeof(struct ListaCategoria));

    (*temp).ident = x;
    (*temp).data = arr; //this is the line that's giving some trouble can someone explain me why?
}

【问题讨论】:

  • scanf("%c[^\n]", &arr); 将在 C 中调用 未定义的行为,因为在需要 char* 的地方传递了 char(*)[MAX]
  • 你的意思是“objective C”开发iOS应用常用的语言吧?
  • temp->datatemp->ident 会更短

标签: c arrays char


【解决方案1】:

要将数据扫描到 C-“字符串”中,请使用 %s%c 仅适用于一个 char

对于扫描到一个数组,你可以传递数组,这样它就会衰减到它的第一个元素的地址,你不需要在它上面使用 address-of 运算符。

scanf("%s[^\n]", arr);

另外你应该告诉scanf()不要溢出通过指定其大小传递的缓冲区(假设#define MAX (42)):

scanf("%41s[^\n]", arr); /* specify one less, as C-"string" always carry 
                            and additional char, the so called `0`-terminator 
                            marking the end of the string. */

用这条线

(*temp).data = arr;

您正在尝试将数组分配给数组。这在 C 中是不可能的。

一般来说,复制数组的内容需要采取其他方法:

  • 循环并分别分配每个元素的值
  • 将源内存的内容复制到目标内存

对于后一种情况,如果

  • 两个数组都是char-arrays
  • 源数组是一个 C-“字符串”

最常见的做法是使用函数strcpy()

strcpy((*temp).data, arr);

这个函数不会复制所有数组的内容,而只复制正在使用的部分,即直到0-终止符,标记检测到的字符串的结尾。

【讨论】:

    猜你喜欢
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    相关资源
    最近更新 更多