简体   繁体   English

用scanf分配指针的char数组

[英]Assigning char array of pointers with scanf

I'm trying to use scanf to fill an array of char pointers to store the input as a string. 我正在尝试使用scanf填充char指针数组,以将输入存储为字符串。 The variable T is used to build an array of size T dynamically. 变量T用于动态构建大小为T的数组。 Then T amount of strings are entered and displayed however when I fill in the array for example if T = 2 the first line could dog and the second line cat, it prints out "cdog" and "cat". 然后输入并显示T数量的字符串,但是当我填写数组时,例如,如果T = 2,则第一行可以跟踪,第二行显示cat,它会打印出“ cdog”和“ cat”。 So the first letter of the first string then the all of the 2nd string. 因此,第一个字符串的第一个字母,然后是第二个字符串的全部。 I'm not sure where my mistake is in using char*. 我不确定在使用char *时我的错误在哪里。 Any help would be appreciated. 任何帮助,将不胜感激。

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

int main()
{
  int T;
  int i;
  scanf("%d",&T);


  char *new_array = (char*)malloc(T * sizeof(char));

  for (i = 0; i < T; ++i)
  {
    scanf("%s", new_array+i);

  }

  for (i = 0; i < T; i++)
  {
    printf("%s\n", new_array+i);
  }
}
  1. Always check the return value of scanf() . 始终检查scanf()的返回值。
  2. You are not allocating space for pointers, but for bytes, which is the main problem, you need 您不是为指针分配空间,而是为字节分配空间,这是主要问题,您需要

     char **new_array = malloc(T * sizeof(char *)); /* ^ ^ */ /* allocate pointer to poitners sizeof(pointer) */ if (new_array == NULL) handleThisErrorAndDoNotTryToWriteTo_new_array(); 

    you will also need space for each string so 您还将需要为每个字符串留出空间,因此

     new_array[i] = malloc(1 + lengthOfTheString); if (new_array[i] == NULL) handleThisErrorAndDoNotTryToWriteTo_new_array_i(); 

    right before scanf() , and instead of scanf("%s", new_array + i) do this 就在scanf()之前,而不是scanf("%s", new_array + i)执行此操作

     scanf("%s", new_array[i]); 

If you enable compiler warnings, the compiler should warn you that you are passing incompatible types to printf() . 如果启用了编译器警告,则编译器应警告您将不兼容的类型传递给printf()

It would also be good, to use a length modifier for scanf() to prevent buffer overflow, and don't forget to call free() when you no longer need the pointers. scanf()使用一个长度修饰符以防止缓冲区溢出,并且当您不再需要指针时不要忘记调用free()也是很好的。

In your code, new_array is of type char * , which is not what you want. 在您的代码中, new_array的类型为char * ,这不是您想要的。 You have to change your definition to 您必须将定义更改为

char *new_array[T] = malloc(T * sizeof(char*));

Then, you can use the scanf() as per your previous code. 然后,您可以按照之前的代码使用scanf()

Do this instead, together with the rest of the body: 相反,与身体的其余部分一起这样做:

int string_size;
//this begins just after reading T
scanf("%d", &string_size);
char **new_arrays = malloc(T * sizeof(char*));
for(i = 0; i < T; i++)
{
    new_arrays[i] = malloc(string_size * sizeof(char));
}

The first malloc is to specify how many strings you want, and the second malloc is to specify how big a string can be. 第一个malloc用于指定所需的字符串数,第二个malloc用于指定字符串的大小。

Further tips: 其他提示:

  1. When you're writing in C, do not cast void* produced by malloc and realloc . 用C编写时,请勿realloc mallocrealloc产生的void*
  2. You should de-allocate the memory used in the reverse way: 您应该以相反的方式取消分配使用的内存:

     for (i = 0; i < T; ++i) { free(new_array[i]); } free(new_array); 
  3. Always check if the memory allocation process is (un)succesful: 始终检查内存分配过程是否成功:

     char **new_arrays = malloc(T * sizeof(char*)); if(new_arrays == NULL) exit(0) //eg for(i = 0; i < T; i++) { new_arrays[i] = malloc(string_size * sizeof(char)); if(new_arrays[i] == NULL) exit(0) //eg } 
  4. Check if the user provides valid values through scanf . 检查用户是否通过scanf提供有效值。

Thanks everyone. 感谢大家。 The length of the strings in the char* array can not be greater than 1000 chars so thats hard coded. char *数组中字符串的长度不能大于1000个字符,因此必须进行硬编码。 Here is the final working code... 这是最终的工作代码...

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

int main()
{
  int T;
  int i;
  scanf("%d",&T);


  char **new_array = malloc(T * sizeof(char*));
  for (i = 0; i < T ; i++)
  {
    new_array[i] = malloc(1000 * sizeof(char));
    scanf("%s", new_array[i]);
  }

  for (i = 0; i < T; i++)
    printf("%s\n", new_array[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM