使用 const 代替变量声明的空指针

Null pointer using const instead of variable declaration

我有一个无法解决的问题。我写了这段代码来打乱数组的元素:

#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;
}

当我运行这个程序时,这是iutput:

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;
}

一切正常。 谢谢

size-1 开始循环,您在 array[size](第一次循环迭代)中指向数组外。

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

您应该尽可能避免转换,而且很少有必要这样做。

除非您计划使用 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;
}