用scanf分配指针的char数组 [英] Assigning char array of pointers with scanf

查看:97
本文介绍了用scanf分配指针的char数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用scanf填充char指针数组,以将输入存储为字符串。变量T用于动态构建大小为T的数组。然后输入并显示T数量的字符串,但是当我填写数组时,例如,如果T = 2,则第一行可以跟踪,第二行显示cat,它将打印出 cdog和 cat。因此,第一个字符串的第一个字母,然后是第二个字符串的全部。我不确定我在使用char *时出错了。任何帮助,将不胜感激。

I'm trying to use scanf to fill an array of char pointers to store the input as a string. The variable T is used to build an array of size T dynamically. 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". 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*. 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. 始终检查 scanf()的返回值。

  2. 您没有为指针分配空间,但是对于字节(这是主要问题),您需要

  1. Always check the return value of 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();

scanf()之前, scanf(%s,new_array + i)的操作

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


如果启用编译器警告,则编译器应警告您将不兼容的类型传递给 printf()

If you enable compiler warnings, the compiler should warn you that you are passing incompatible types to printf().

使用a scanf()的长度修饰符,以防止缓冲区溢出,不要忘记调用 free()不再需要指针。

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分配指针的char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆