动态分配的字符串数组

时间:2015-07-09 14:54:23

标签: c pointers dynamic-memory-allocation

该程序应该动态存储输入指针的每个字符串。每个指针都是指针数组的一部分,这些指针将共同保存所有字符串。当用户输入空单词或NULL时,它应该退出。我的问题是代码只是跳过NULL条件语句。我看到了一些类似的帖子,并且已经使用了几个小时,但是无法解决它。

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

void readWord(char wordChar[], int MAX_CHARS);

int main()
{
    int MAX_CHARS = 20;
    int wCount = 0;

    char *wordArray[wCount]; // Array of pointers that will each point to wordChar
    char wordChar[MAX_CHARS];

    int i;
    for(i = 0;;i++)
    {
        wCount++;

        printf("Enter word: ");
        readWord(wordChar, MAX_CHARS); //Reads one word at a time


        //Dynamically store each 
        wordArray[i] = (char*) malloc((int) strlen(wordChar) * (int) sizeof(char));
        wordArray[i] = wordChar;
        printf("%s \n", wordArray[i]); //Troubleshooting *********************

        // If loop ends scanning when word is NULL 
        if(wordArray[i] == 'NULL')
        {   
            printf("if loop");
            break;
        }
        else printf("no loop");
    }

}


/***********************************************************/

void readWord(char wordChar[], int MAX_CHARS)
{
    int letter, i = 0;

    while((letter = getchar()) != '\n')
    {
        if(i < MAX_CHARS)
        {
            wordChar[i] = letter; 
            i++;
        }
    }

    wordChar[i] = '\0';
}

2 个答案:

答案 0 :(得分:2)

简短而无用的摘要是:#include string.h if(wordArray[i] == 'NULL') ;用它!

你试图直接比较两个指针。

'NULL'

这一行将wordArray [i]的指针值看作多字符文字'NULL'的值(注意我没说字符串:你用的是单引号这里,wordArray[i]的整数值为0x4e554c4c;请参阅https://stackoverflow.com/a/7459943/510299)。如果==指向地址0x12345678,那么这是将0x12345678与0x4e554c4c进行比较并发现它们不相等。

你想要的是比较字符串。在C中,你不能用==执行此操作,因为C字符串是char数组或指向字符的指针;如上所述,strcmp比较指针(地址)值。

解决方案,使用if(strcmp(wordArray[i], "NULL") == 0)

char *wordArray[wCount];

(注意使用双引号。)

编辑:另请注意,wCount == 0时会声明wordArray。这名义上意味着你试图声明一个长度为0的数组,这是未定义的行为。您需要声明wordArray[i] = (char*) malloc((int) strlen(wordChar) * (int) sizeof(char)); 一些长度(可能是您可以存储的最大字数)。 [感谢riodoro1在评论中指出这一点。]

你在C中用字符串操作做了类似的错误:

wordArray[i]

该行将指针wordArray[i] = wordChar; 设置为一些新分配的内存。

wordArray[i]

然后该行继续将指针wordChar更改为指向存储读取字的原始位置。哎呀。下次进行此循环时,wordArray[i]会发生变化,wordChar指向malloc ...所以新单词“替换”所有之前的单词。

解决方案?您需要将字符串复制到仅strcpy()'的内存中。使用printf("if loop");

;WITH dates AS 
(
    SELECT CONVERT(datetime,cast(month(getdate())-2 as varchar(2))+'/'+cast(day(getdate()) as varchar(2))+'/'+ cast(year(getdate()) as varchar(4))) as Date,' ' as eid
    UNION ALL
    SELECT DATEADD(d,1,[Date]),' ' as eid
    FROM dates 
    WHERE DATE < GETDATE()
)
select  datename(DD,dates.date)+' '+datename(MM,dates.date)+' '+ datename(YYYY,dates.date) from dates
where datename(dw,dates.date) = 'Monday'

条件(if)语句不是一种循环。

答案 1 :(得分:0)

#include <stdio.h>
#include <stdlib.h> //for realloc and free (malloc)
#include <string.h>

void readWord(char wordChar[], int MAX_CHARS);

int main(void){
    int MAX_CHARS = 20;
    int wCount = 0;
    char **wordArray = NULL; // Array of pointers that will each point to wordChar
    char wordChar[MAX_CHARS];

    int i;
    for(i = 0;;i++){
        printf("Enter word: ");
        readWord(wordChar, MAX_CHARS); //Reads one word at a time
        if(*wordChar == '\0' || strcmp(wordChar, "NULL") == 0){//empty word or "NULL"
            putchar('\n');
            break;
        }

        wCount++;
        wordArray = realloc(wordArray, wCount * sizeof(*wordArray));//check omitted
        //Dynamically store each
        wordArray[i] = malloc(strlen(wordChar) + 1);//+1 for NUL
        strcpy(wordArray[i], wordChar);//copy string
    }
    //check print and free
    for(i = 0; i < wCount; ++i){
        printf("'%s'\n", wordArray[i]);
        free(wordArray[i]);
    }
    free(wordArray);

    return 0;
}

void readWord(char wordChar[], int MAX_CHARS){
    int letter, i = 0;

    while((letter = getchar()) != '\n' && letter != EOF){
        if(i < MAX_CHARS -1)//-1 for NUL, or char wordChar[MAX_CHARS+1];
            wordChar[i++] = letter; 
        else
            ;//drop letter upto newline
    }
    wordChar[i] = '\0';
}