使用null第一个索引传递非空字符串数组

时间:2017-02-05 08:02:37

标签: c arrays access-violation

我需要将一个字符串数组传递给函数,我只想填充数组的第三项,并保留所有其他项NULL,这样我就可以在我传递数组的函数中填充它至。但不幸的是,它为所有项目读取了传递的数组NULL。我无法弄清楚为什么会这样?

它会将Msg数组视为全部NULL,并且不会读取已设置的第7项。

这是我的代码:

void MSGCONT()
{
    char *Front= "0811";
    char *DateTime = "1701231335";
    char *Msg[130];
    int i = 0;

    while (i < 130) {
        Msg[i] = '\0';
        i++;
    }

    Msg[7] = &DateTime[0];

    Build(Msg, Front);
}

char *Build(char *Msg[130], char *Front) {
    Msg[0] = Front;

    while (Msg[1] == "") { // access violation reading location error.
        // some code
    }
}

1 个答案:

答案 0 :(得分:1)

首先,您需要决定是否要为未填充的数组项传递NULL或空字符串。我建议使用NULL来减少模糊,但出于实际原因,你可能会选择空字符串。 如果选择使用NULL,则必须先检查数组中的指针,然后再尝试访问它们所指向的内容。

无论哪种方式,都应该将数组中的元素数作为参数传递给Build。

让我们看一下带有NULL的版本:

#include <stdio.h>
#define NUMBER_OF_MESSAGES 130

char* Build(char* Msg[], int MsgCnt, char *Front);

void MSGCONT()
{
    char* Front= "0811";
    char* DateTime =  "1701231335";
    char* Msg[NUMBER_OF_MESSAGES];
    int i =0;

    while( i < NUMBER_OF_MESSAGES)
    {
         Msg[i++] = NULL;
    }

    Msg[7] = DateTime;

    Build(Msg, NUMBER_OF_MESSAGES, Front);

}

char* Build(char* Msg[], int MsgCnt, char *Front)
{
   Msg[0] = Front;

   for (int i=1; i<MsgCnt; i++) 
   {
     if(Msg[i] != NULL)
     {
       printf("%ith item contains %s\n", i, Msg[i]);
     }
   }

   return "whatever";
}

int main(int argc, char*argv[]) {
   MSGCONT();
   return 0;
}

这是一个空字符串的版本:

#include <stdio.h>
#include <string.h>

#define NUMBER_OF_MESSAGES 130

char* Build(char* Msg[], int MsgCnt, char *Front);

void MSGCONT()
{
    char* Front= "0811";
    char* DateTime =  "1701231335";
    char* Msg[NUMBER_OF_MESSAGES];
    int i =0;

    while( i < NUMBER_OF_MESSAGES)
    {
         Msg[i++] = "";
    }

    Msg[7] = DateTime;

    Build(Msg, NUMBER_OF_MESSAGES, Front);

}

char* Build(char* Msg[], int MsgCnt, char *Front)
{
   Msg[0] = Front;

   for (int i=1; i<MsgCnt; i++) 
   {
     if(strcmp(Msg[i], "")!=0)
     {
       printf("%ith item contains %s\n", i, Msg[i]);
     }
   }

   return "whatever";
}

int main(int argc, char*argv[]) {
   MSGCONT();
   return 0;
}