在c中声明和复制char字符串数组

时间:2017-10-02 12:48:28

标签: c arrays malloc

我创建了一个c程序,尝试使用单独的方法将一个字符串数组的值添加到另一个字符串:

#include <stdio.h>
#include <stdlib.h>

void charConv(char *example[])
{
  example= (char* )malloc(sizeof(char[4])*6);
  char *y[] = {"cat", "dog", "ate", "RIP", "CSS", "sun"};

  printf("flag\n");

  int i;
  i=0;

  for(i=0; i<6; i++){
    strcpy(example[i], y[i]);
  }
}

int main() {
  char *x[6];
  charConv( *x[6]);

  printf("%s\n", x[0]);
}

然而,它不断返回分段错误。我只是开始学习如何使用malloc和c一般,并且一直困惑我找到解决方案。

2 个答案:

答案 0 :(得分:1)

要明确指出您的问题:您发送*x[6](此处为charConv( *x[6]);),这是 7 的第一个字符(!!! )字符串(请记住,C是零基础索引)在6个字符串的数组中,你没有malloc - &gt;使用你不拥有的记忆 - &gt; UB。

我应该注意的另一件事是char[] vs char * []。使用前者,您可以strcpy进入字符串。它看起来像这样:

'c' | 'a' | 't' | '\0' | 'd' | 'o' | 'g' | ... [each cell here is a `char`]

后者(你使用过的)不是char的连续块,而是char *的数组,因此你应该做的就是为数组中的每个指针分配内存并复制进去。那看起来像是:

 0x100 | 0x200 | 0x300... [each cell is address you should malloc and then you would copy string into]

但是,您的代码中也存在一些问题。以下是一个固定版本,附有解释:

#include <stdio.h>
#include <stdlib.h>

void charConv(char *example[])
{
  // example= (char* )malloc(sizeof(char[4])*6); // remove this! you don't want to reallocate example! When entering this function, example points to address A but after this, it will point to address B (could be NULL), thus, accessing it from main (the function caller) would be UB ( bad )

  for (int i = 0; i < 6; i++)
  {
    example[i] = malloc(4); // instead, malloc each string inside the array of string. This can be done from main, or from here, whatever you prefer
  }


  char *y[] = {"cat", "dog", "ate", "RIP", "CSS", "sun"};

  printf("flag\n");

 /* remove this - move it inside the for loop
  int i;
  i=0;
  */

  for(int i=0; i<6; i++){
    printf("%s\t", y[i]); // simple debug check - remove it 
    strcpy(example[i], y[i]);
    printf("%s\n", example[i]); // simple debug check - remove it 
  }
}

int main() {
  char *x[6];
  charConv( x); // pass x, not *x[6] !!

  for (int i = 0; i < 6; i++)
  {
    printf("%s\n", x[i]);  // simple debug check - remove it 
  } 
}

正如@MichaelWalz所提到的,使用硬编码值并不是一个好习惯。我把它们留在这里,因为它是一个小片段,我认为它们是显而易见的。尽管如此,尽量避免使用它们

答案 1 :(得分:0)

您需要首先了解指针和其他一些主题,以及如何将字符串数组传递给C等函数。 在你的程序中,你在charConv()中传递* x [6],这是一个字符。

在您的计划中进行更正 -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void charConv(char *example[], int num)
{
  int i;

  for (i = 0; i < num; i++){
      example[i] = (char* )malloc(sizeof(char)*4);
  }

  const char *y[] = {"cat", "dog", "ate", "RIP", "CSS", "sun"};

  for(i = 0; i < num; i++){
      strcpy(example[i], y[i]);
  }
}

int main() {
  char *x[6];
  int i = 0;

  charConv(x, 6);

  /* Print the values of string array x*/
  for(i = 0; i < 6; i++){
      printf("%s\n", x[i]);
  }

  return 0;
}