字符数组目标C



我有一个问题与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?
}

要将数据扫描成C-"string",请使用%s, %c只能用于一个char

同样,对于扫描到数组,你将传递数组,这样它将衰减到它的第一个元素的地址,你不需要对它使用地址操作符。

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语言中是不可能的。

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

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

对于后一种情况和if

  • 两个数组都是char -arrays
  • 源数组是一个C-"string"
最常用的方法是使用函数strcpy():
strcpy((*temp).data, arr);

此函数不复制数组的所有内容,而只复制正在使用的部分,即直到0 -终止符,标志着所检测字符串的结束。

相关内容

最新更新