简体   繁体   English

动态分配数组的C问题

[英]C issue with dynamically allocating array

The input file for my program has the first line containing an int (call it N) that will signify how many following integers there will be (each integer on a new line). 我程序的输入文件的第一行包含一个int(称为N),该int表示将有多少个后续整数(每个新行中的整数)。 Then it should read the integers into num_array and print them out. 然后它将整数读入num_array并打印出来。 My issue is that num_array is not being allocated properly I think. 我的问题是num_array分配不正确。 The debugging statements in the code will print out 8 being the sizeof(num_array) no matter what N is. 无论N是多少,代码中的调试语句都会输出8,即sizeof(num_array)。

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

int *num_array;

int main (int argc, char**argv){
    int numThreads = (int) argv[1];
    char *inputFile = argv[2];
    int N = 0;

    char line[20];
    FILE *file = fopen(inputFile, "r");

    int fileCounter = 0;

    while(fgets(line, sizeof(line), file)) {
        if (fileCounter==0){
            N = atoi(line);
            num_array = malloc(sizeof(int)*(N+1));
        }
        else{
            num_array[fileCounter-1] = atoi(line);
        }
        fileCounter++;
    }
    fclose(file);
    int i;

    printf("%d", sizeof(num_array));
    printf("\n");
    printf("\n");
    for(i = 0; i<sizeof(num_array); i++){
        printf("%d\n", num_array[i]);
    }
    return 0;
}

Input file example: 输入文件示例:

9
10
9
3
212
56
99
4
5
6

will print out: 将打印出:

8  
10
9
3
212
56
99
4
5

As you can see, the last element of the array is cut off (does not print 6) and it appears num_array is not being sized properly (should contain N integers with N being the int at the first line of the input file) 如您所见,数组的最后一个元素被切除(不打印6),并且num_array的大小似乎不正确(应包含N个整数,在输入文件的第一行中N为int)

Many problems with your program: 您的程序存在许多问题:

  1. The first line of your main() function has a very severe mistake 您的main()函数的第一行有一个非常严重的错误

     int numThreads = (int) argv[1] 

    in c casting does not convert the type, this conversion is certainly possible, but doesn't give the result you expect, you need something like this 在c强制转换中不会转换类型,这种转换当然是可能的,但是没有给出您期望的结果,您需要这样的东西

     char *endptr; int numThreads = strtol(argv[1], &endptr, 10); if (*endptr != '\\0') { printf("`%s' cannot be converted to an integer\\n", argv[1]); return -1; } 
  2. You didn't make sure that there was a parameter provided to your program's command line, you need to check that, argc contains the number of command line arguments passed to your program + the argv[0] , so you must check 您不确定要向程序的命令行提供任何参数,需要检查一下, argc包含传递给程序的命令行参数数量+ argv[0] ,因此必须检查

     if (argc < 2) { printf("Use: %s NumberOfThreads, where NumberOfThreads is `int'\\n", argv[0]); return -1; } 
  3. You don't check if fopen() returns NULL , that would cause more issues when you fgets() the file pointer. 您无需检查fopen()返回NULL ,这将在fgets() file指针时引起更多问题。

  4. The sizeof operator does not give the length of an array it gives the number of bytes occupied by the array, and you variable is not an array, it's a pointer, so the sizeof operator in this case is giving the size of a pointer. sizeof运算符不给出数组的长度,它给出该数组占用的字节数,并且您的变量不是数组,而是指针,因此在这种情况下, sizeof运算符给出的是指针的大小。

    It turns out that your file contains 9 values and in your platform the pointer size is 8 , so sizeof(num_array) is 8 which is 9 - 1 hence your are missing one value, you already have the number of elements of the array N , so use it. 事实证明,文件包含9值,并在平台的指针大小是8 ,所以sizeof(num_array)8 ,其是9 - 1因此你丢失一个值,则已经有该阵列的元件的数量N ,所以用吧

  5. You never call free() . 您永远不会调用free()

This is a version of your code, it's fixed and it's made safer 这是您代码的一个版本,已经修复,并且更加安全

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

int *num_array;

int main (int argc, char**argv) 
 {
    char  line[20];
    /*int   numThreads  = 1;*/
    char *inputFile   = "data.dat";
    int   N           = 0;
    int   fileCounter = 0;
    int   i           = 0;
    FILE *file = fopen(inputFile, "r");
    if (file == NULL)
        return -1;
    while (fgets(line, sizeof(line), file) != NULL)
     {
        if (fileCounter == 0)
         {
            N         = atoi(line);
            num_array = malloc((1 + N) * sizeof(int));
            if (num_array == NULL)
             {
                fclose(file);
                return -1;
             }
         }
        else
         {
            num_array[fileCounter - 1] = atoi(line);
         }
        fileCounter++;
     }
    fclose(file);

    printf("%ld", sizeof(num_array));
    printf("\n");
    printf("\n");
    for (i = 0 ; i < N ; i++)
     {
        printf("%d\n", num_array[i]);
     }
    free(num_array);
    return 0;
 }

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

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