简体   繁体   English

在数组中使用C字符串

[英]Using C Strings in an array

This is a program I wrote (not including "string.h") which is meant to convert a string to upper case. 这是我编写的程序(不包括“ string.h”),旨在将字符串转换为大写。 It works with a single string - so far so good. 到目前为止,它只适用于单个字符串。

I run into trouble when I try to create an array of strings so I can test various strings in turn as part of a loop. 尝试创建字符串数组时遇到麻烦,因此我可以依次测试各种字符串作为循环的一部分。

So, I don't understand why the program works when my string is declared as char test_string[] = "TEST"; 因此,我不明白当我的字符串声明为char test_string[] = "TEST";时,为什么程序可以运行test_string[] = "TEST"; but it does not work when I declare an array of pointers to strings. 但是当我声明一个指向字符串的指针数组时它不起作用。

This is the working single string version (followed by the non-working array of strings version): 这是正常工作的单字符串版本(随后是无效工作的字符串版本):

#include <stdio.h>

void toAlpha(char*);
int str_len(char*);

int main()
{
    char test_string[] = "TEST";            /* string to test */
    char *pStr = NULL;                  /* pointer to string */

        pStr = test_string;
        toAlpha(pStr);
        printf("%s\n", pStr);


    return 0;
}


void toAlpha(char *arg)
{
    int i = 0;                  /* counter - original string*/
    int j = 0;                  /* counter - temp string */

    /* check each character in original and save alphabetic characters only */
    for ( i = 0; i < str_len(arg); i++ )
    {
        if( *(arg + i) >= 'a' && *(arg + i) <= 'z' )
            *(arg + j++) = *(arg + i);
        else
            if ( *(arg + i) >= 'A' && *(arg + i) <= 'Z' )
                *(arg + j++) = *(arg + i) - 'A' + 'a';
    }

    /* add a null character terminator */
    *(arg + j) = '\0';

}


int str_len(char *arg)
{
    /*return count of letters in a C string */
    int i = 0;
    if ( arg != NULL )
        while ( arg[i] != '\0' )
            i++;
    return i;
}

This is the non-working version with the failed attempt to use an array (it compiles but crashes at runtime): 这是无法正常使用的版本,尝试使用数组失败(它可以编译,但在运行时崩溃):

#include <stdio.h>

void toAlpha(char*);
int str_len(char*);
void palindrome(char*);

int main()
{
    char *test_strings[1];                      /* strings to test */
    char *pStr = NULL;                          /* pointer to string */
    int i = 0;                                  /* loop counter */

    test_strings[0] = "TEST1";
    test_strings[1] = "TEST2";

    for (i = 0; i < 1; i++){
        pStr = test_strings[i];
        toAlpha(pStr);
        printf("%s\n", pStr);
    }

    return 0;
}


void toAlpha(char *arg)
{
    int i = 0;                  /* counter - original string*/
    int j = 0;                  /* counter - temp string */

    /* check each character in original and save alphabetic characters only */
    for ( i = 0; i < str_len(arg); i++ )
    {
        if( *(arg + i) >= 'a' && *(arg + i) <= 'z' )
            *(arg + j++) = *(arg + i);
        else
            if ( *(arg + i) >= 'A' && *(arg + i) <= 'Z' )
                *(arg + j++) = *(arg + i) - 'A' + 'a';
    }

    /* add a null character terminator */
    *(arg + j) = '\0';

}


int str_len(char *arg)
{
    /*return count of letters in a C string */
    int i = 0;
    if ( arg != NULL )
        while ( arg[i] != '\0' )
            i++;
    return i;
}

I found the error. 我发现了错误。 You can't modify string literal. 您不能修改字符串文字。 To fix this you need to substitute the following: 要解决此问题,您需要替换以下内容:

test_strings[0] = "TEST1";
test_strings[1] = "TEST2";

by: 通过:

test_strings[0] = (char *) malloc(sizeof(char) * (strlen("TEST1") + 1)); // +1 for the \n
test_strings[1] = (char *) malloc(sizeof(char) * (strlen("TEST2") + 1)); // +1 for the \n
strcpy(test_strings[0], "TEST1");
strcpy(test_strings[1], "TEST2");

Since you don't want to include string.h it seems that you need to implement the function strcpy. 由于您不想包含string.h,因此似乎需要实现strcpy函数。 Also you need to include stdlib.h (because of malloc). 另外,您还需要包括stdlib.h(由于使用了malloc)。

You have to include "stdio.h" for NULL macro and printf. 您必须为空宏和printf包括“ stdio.h”。 The runtime problem is because you have an array of 1 element and you are assigning "TEST2" into the non-existing second position. 运行时问题是因为您有一个由1个元素组成的数组,并且将“ TEST2”分配给了不存在的第二个位置。 I don't understand what you want to do in toAlpha(). 我不明白您想在toAlpha()中做什么。

#include <stdio.h>

// ...

int main()
{
    char *test_strings[2];                      /* strings to test */
    char *pStr = NULL;                          /* pointer to string */

    test_strings[0] = "TEST1";
    test_strings[1] = "TEST2";

    for (int i = 0; i < 2; ++i)
    {
        pStr = test_strings[i];
        toAlpha(pStr);
        printf("%s\n", pStr);
    }

    return 0;
}

// ...

Okay. 好的。 Rewrote both programs. 重写两个程序。 Hopefully better this time. 希望这次更好。 But used string.h library in lieu of writing my own strcpy function. 但是用string.h库代替编写自己的strcpy函数。 Though I didn't describe toAlpha properly. 虽然我没有正确地描述Alpha。 It's meant to remove any non-alphabetic characters, and to return the result as all lower-case letters. 这意味着要删除所有非字母字符,并将结果作为所有小写字母返回。 --Topsail --Topsail

First program (single string): 第一个程序(单字符串):

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

    void toAlpha(char*);
    int str_len(char*);

    int main()
    {
        char test_string[100];              /* string to test */
        char *pStr = NULL;                  /* pointer to string */

            strcpy(test_string, "Test-A");
            pStr = test_string;
            toAlpha(pStr);
            printf("%s\n", pStr);


        return 0;
    }


    void toAlpha(char *arg)
    {
        int i = 0;                  /* counter - original string*/
        int j = 0;                  /* counter - temp string */

        /* check each character in original and save alphabetic characters only */
        for ( i = 0; i < str_len(arg); i++ )
        {
            if( *(arg + i) >= 'a' && *(arg + i) <= 'z' )
                *(arg + j++) = *(arg + i);
            else
                if ( *(arg + i) >= 'A' && *(arg + i) <= 'Z' )
                    *(arg + j++) = *(arg + i) - 'A' + 'a';
        }

        /* add a null character terminator */
        *(arg + j) = '\0';

    }


    int str_len(char *arg)
    {
        /*return count of letters in a C string */
        int i = 0;
        if ( arg != NULL )
            while ( arg[i] != '\0' )
                i++;
        return i;
    }

second program with array of strings: 第二个带有字符串数组的程序:

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

    void toAlpha(char*);
    int str_len(char*);
    void palindrome(char*);

    int main()
    {
        char *test_strings[2];                      /* strings to test */
        char *pStr = NULL;                          /* pointer to string */
        int i = 0;                                  /* loop counter */

        test_strings[0] = (char *) malloc(sizeof(char) * (strlen("TEST-A") + 1));
        strcpy(test_strings[0], "TEST-A");
        test_strings[1] = (char *) malloc(sizeof(char) * (strlen("TEST-1") + 1));
        strcpy(test_strings[1], "TEST-B");


        for (i = 0; i < 2; i++){
            pStr = test_strings[i];
            toAlpha(pStr);
            printf("%s\n", pStr);
            free(pStr);
        }

        return 0;
    }


    void toAlpha(char *arg)
    {
        int i = 0;                  /* counter - original string*/
        int j = 0;                  /* counter - temp string */

        /* check each character in original and save alphabetic characters only */
        for ( i = 0; i < str_len(arg); i++ )
        {
            if( *(arg + i) >= 'a' && *(arg + i) <= 'z' )
                *(arg + j++) = *(arg + i);
            else
                if ( *(arg + i) >= 'A' && *(arg + i) <= 'Z' )
                    *(arg + j++) = *(arg + i) - 'A' + 'a';
        }

        /* add a null character terminator */
        *(arg + j) = '\0';

    }


    int str_len(char *arg)
    {
        /*return count of letters in a C string */
        int i = 0;
        if ( arg != NULL )
            while ( arg[i] != '\0' )
                i++;
        return i;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM