通过指针

时间:2017-06-23 07:07:17

标签: c arrays pointers char

我正在尝试将更新的char数组传递回原始main()函数,但是当我尝试使用指针复制数组时,它会让我“Char ”级别不同来自char的间接()[15]'

这是一个ISBN验证程序。

这是:

int main(void)
{
    int divisible;
    char choice, trash;
    char code[15];


    do
    {
        printf("Enter an ISBN (book) number:\n");
        fgets(code, 15, stdin);

        printf("The ISBN entered is:%s\n", code);
        divisible = testISBN(&code);
        if (divisible == 1)
            printf("\n\n\tValid ISBN Number\n");
        else
            printf("\n\n\tInvalid ISBN Number\n");

        printf("\nDo you wish to continue? (Y/N)\n");
        choice = getchar();
        trash = getchar();
    } while (toupper(choice) != 'N');

    return 0;
}


int testISBN(char *code)
{
    int i;
    int sum = 0;
    int weight = 10;
    char codefinal[10];
    int x = 0;
    for (i = 0; i<15; i++)
    {
        int chVal;
        if ((i == 9) && (toupper(code[i]) == 'X'))
        {
            printf("%c",code[i]);
            chVal = 10;
        }
        else
        {
            chVal = code[i] - '0';
        }
        if (chVal == 0 || chVal == 1 || chVal == 2 || chVal == 3 || chVal == 4 || chVal == 5 || chVal == 6 || chVal == 7 || chVal == 8 || chVal == 9) {
            char y = (char)chVal;
            codefinal[x] = y;
            x++;
        }

        sum += chVal * weight;
        weight--;
    }
    printf("sum is %d", sum);

    for  (i = 0; i < 15; i++) {
        *code[i] = codefinal[i];
        printf("%c", code);
    }
    return (sum % 11) == 0;
}

在最底层我说*code[i] = codefinal[i]是我遇到问题的地方。我只是想通过指针将我新更新的数字数组传回给我的主。

2 个答案:

答案 0 :(得分:0)

只需将代码传递给指针即可。

char code[15];
divisible = testISBN(code);

您可能希望将testISBN签名更改为

int testISBN(char code[15]);

这样,如果搞乱索引,你就有更高的机会获得编译器警告。

简单示例:

#include <stdio.h>

void func(char arr[3]) {
 arr[0] = 'H';
 arr[1] = 'i';
 arr[2] = 0;
}

int main() {
  char arr[3] = {0};
  func(arr);
  printf("%s", arr);
}

打印“嗨”

正如评论者所提到的,您的代码还有其他问题,例如内存超出访问权限。为了让您的生活更轻松地花费一些时间阅读编译器的手册并学习如何打开所有警告,它们会在大多数情况下指出代码问题。

答案 1 :(得分:0)

在您的代码中进行以下更改:

  • 将函数int testISBN(char* code)的原型更改为int testISBN(char code[])
  • 将来电从testISBN(&code);更改为testISBN(code);
  • 将行*code[i] = codefinal[i];更改为code[i] = codefinal[i];
  • 在行printf("%c", code);中,您打印的不是code[]的值,而是打印地址printf("%c", code[i]);。所以将其更改为code[]注意 if (chVal == 0 || chVal == 1 || chVal == 2 || chVal == 3 || chVal == 4 || chVal == 5 || chVal == 6 || chVal == 7 || chVal == 8 || chVal == 9)也包含一些不可打印的字符。
  • 建议:为简单起见,您可以将第if((chVal >= 0) && (chVal <= 9))行更改为=IF($L3=0,TRUE)