如何创建一个未定义大小的数组?

时间:2014-09-04 10:59:07

标签: c arrays

这是我对LUHN算法的实现 在我的输入代码中,我想创建一个值的数组,其长度可以根据用户输入而变化。 下面是我试过但似乎没有工作......如果我需要使用malloc函数我该怎么用呢?除此之外一切正常,还建议进行一些优化。

#include<stdio.h>

int main()

{  char a[100];
   int sum=0,c=0,i;


     printf("enter the card you use\n");
     scanf("%16s",&a[i]);

     for(int m=0;a[m]!='\0';m++){

      c++;
     }

    for(int j=0;j<c;j++){
    int k,l;
    if(j%2==0){
    k=a[j]%10;
    l=a[j]/10;
    a[j]=k+l;   
    sum=sum + a[j];  
    }      
    else{
    sum = sum + 2*a[j];
    } 
    }                  
    if(sum % 10 ==0 && c==13)                   
    printf("VISA\n");
    else if(sum % 10==0 && c==16)
    printf("MASTERCARD\n");
    else if(sum % 10==0 && c==15)
    printf("AMERICAN EXPRESSWAY\n");
    else
    printf("INVALID\n");

    return 0;
}

2 个答案:

答案 0 :(得分:2)

您的代码存在一些问题。

对于一个:您没有初始化a,但在for上有for(int i=0;a[i]!='\0';i++)循环条件。

问题:

如果您在运行时知道所需数组的长度,则可以使用

为其分配堆内存
void * array_ptr = malloc(size_of_array_element * num_elements);

或在堆栈上(C99及以上):

type array[num_elements];

如果数组的大小在整个运行时间内发生变化,那么您必须使用malloc(或calloc)进行分配,并将其调整为nessessary:

void * resized_array_ptr = realloc(array_ptr, size_of_array_element * num_elements);

答案 1 :(得分:1)

  

我想创建一个值的数组,其长度可以根据不同而变化   用户输入。

您可以在用户输入后定义数组,如

int userinput;
scanf("%d\n",&userinput);
int arr[userinput];

使用malloc,您可以通过

完成
int *arr= malloc(sizeof(int)*userinput);