空指针使用const而不是变量声明

时间:2016-12-28 13:23:35

标签: c arrays variables const shuffle

我有一个问题,我无法弄清楚。我编写了这段代码来改组数组的元素:

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

const char *array[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

int main(int argc, char **argv)
{
 int i, tmp, randomize, size;

 size = sizeof(array)/sizeof(*array);

 srand(time(NULL));

 for(i=size;i>0;i--){
  randomize=0+(rand()%size);
  tmp=(int)array[i];
  array[i]=array[randomize];
  array[randomize]=(char*)tmp;
 }

 for(i=0;i<size;i++)
  printf("%s", array[i]);   
    return 0;
}

当我运行程序时,这就是输出:

azlngiwexbv(null)uscphqjyrodmtk

我无法理解为什么指针有时为空,我无法理解为什么,以这种方式更改源代码:

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

int main(int argc, char **argv)
{
 char *array[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
 int i, tmp, randomize, size;

 size = sizeof(array)/sizeof(*array);

 srand(time(NULL));

 for(i=size;i>0;i--){
  randomize=0+(rand()%size);
  tmp=(int)array[i];
  array[i]=array[randomize];
  array[randomize]=(char*)tmp;
 }

 for(i=0;i<size;i++)
  printf("%s", array[i]);    
 return 0;
}

一切正常。 感谢。

2 个答案:

答案 0 :(得分:3)

size-1开始循环,你指出array[size]中的数组(第一次循环迭代)。

 for (i=size-1; i>=0; i--)

答案 1 :(得分:0)

你应尽可能避免施法,而且很少这样做。

除非您打算使用argcargv[],否则请使用main()int main(void)的更简单表单。这将删除一些编译器警告,您应该启用这些警告;删除编译器发出的所有警告。

您将char的指针投向int以将其存储在tmp中,然后将tmp投回(char *)。只需将tmp声明为指向char的指针即可。第一个循环从size向下计数到0;这是从数组边界开始的,但为什么不使用传统的循环结构:for (i = 0; i < size; i++)?此外,您应该考虑将size_t用于数组索引;它是一个无符号整数类型,保证能够保存任何数组索引,也是sizeof运算符返回的类型。

此外,在您的第一个版本中,您已将array声明为指向const char的指针数组。您可以执行此操作,但需要临时存储变量tmp才能同意const类型限定符。

以下是具有上述更改的代码。没有强制转换,它在没有警告的情况下编译,并且有效。

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

int main(void)
{
    const char *array[] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

    const char *tmp;
    size_t i, size;
    int randomize;

    size = sizeof(array) / sizeof(*array);

    srand(time(NULL));

    for(i = 0; i < size; i++){
        randomize = (rand() % size);
        tmp = array[i];
        array[i] = array[randomize];
        array[randomize] = tmp;
    }

    for(i = 0; i < size; i++)
        printf("%s", array[i]);
    putchar('\n');

    return 0;
}