我试图将整数变量中的单个数字分配给c中的动态数组。但由于某种原因它不起作用

问题描述 投票:0回答:1

所以我试图测试这段代码,但它似乎没有按预期工作。我以前没有使用过 C,我正在为 CS50 这样做(那些熟悉第一周的人)。

所以基本上,我有一个整数,比如说 12345。我试图将第一个数字 (1) 分配给动态数组的索引 0 等等。

但是代码无法正常工作,那么我是否需要了解一些关于我错过的数组的信息?

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




int countDigits(int num) //this gives the length of the integer
{
    int count = 0;

    while(num != 0)
    {
        count++;
        num = num/10;
    }
    return count;
}


int main(void)
{
    int num = get_long("num: ");

    int length = countDigits(num);

    printf("%d \n", length); //printing test to see if it has returned the correct length, and it does

    int* array; //declare the pointer

    array = (int*) malloc(length * sizeof(int));  // declare the dynamic array

    for(int i = 0; i < length ;i ++)
    {
        printf("%d", array[i]);  //print out the array first to see the content
    }
    printf("\n");

    for(int k = 0; k < 2 ; k ++)
    {
        array[length] = (num % 10);  //this is just a testing enviroment for me to assign numbers (i am currently keeping it two digits)
        num = num/10;
        length --;
    }

    for(int j = 0; j < 2 ;j ++)
    {
        printf("%d \n", array[length]);  //once again i print out the content and see if its correct and its not
    }
}

我输入 12,它打印长度 2,这是正确的,然后它打印赋值之前的数组,这可能是正确的,但它在理论上应该给出 1 和 2 时仍然返回零。

arrays c variable-assignment
1个回答
0
投票

主要问题是这个作业:

array[length] = (num % 10)

当循环开始时,您分配给一个超出数组范围的元素。超出数组范围(固定或动态)会导致未定义的行为

使用

lenght - 1
作为索引,或
--length
。但在这两种情况下,您都需要明确检查
length > 0

© www.soinside.com 2019 - 2024. All rights reserved.