持续/定义未使用的变量从无关变量

问题描述 投票:0回答:2

Scenario

我有一个奇怪的错误,当我向代码添加随机变量时,它会更改输出。我弄清楚是什么原因引起了问题,但是我不确定为什么会导致问题。

该代码旨在使用

Luhns算法验证信用卡号。它是EDX CS50课程的一部分,但是我决定在没有其自定义库的情况下尝试它,以尽可能地学习。

我遇到的问题是,如果我运行下面的代码,那么答案就会出现错误(即,附加到整数输出的“ 9”)。现在,如果我要么取消按要求int random_integer = 0;

char random_character = 'M';
,则输出完全按预期工作。 wrong输出(留下那些随机变量评论):209

纠正输出(将其中一个(或两者)删除这些随机变量):
    20
  • 
    
  • 足够了,我注意到,如果我更改为
  • char sum_to_str[3];
    ,问题就完全消失了。
    
    请让我知道您的想法,因为我更新了C,并且对理解细微差别很感兴趣。
  • 代码
char sum_to_str[10];

我尝试了以下内容:
COMPONT/UNCOMENT the the the theRepopperting

添加

#include <stdio.h> // For Standard Input/Output #include <stdlib.h> // For the atoi() function #include <string.h> // For the strchr() and strlen() functions // This value is the length plus one #define MAX_INPUT_LENGTH 255 int main(void) { char user_input[MAX_INPUT_LENGTH]; char *p; // Output CLI instructions printf("Welcome to the Credit Card Validator!!\n"); printf("INSTRUCTIONS: At the prompt, please provide a CC number.\n"); printf("NOTES ON LENGTH: Visa -> 13 || 16, AmEx -> 15 and MC -> 16\n"); // Algorithm char example_card_num[] = "4003600000000014"; // Check the length int card_num_length = strlen(example_card_num); int skip_flag = 0; int sum_of_values = 0; char value_at_index; char str_of_evens[20]; for (int i = card_num_length - 1; i >= 0; i--) { char sum_to_str[3]; switch (skip_flag) { case 0: // Add 'odd' values together value_at_index = example_card_num[i]; sum_of_values = sum_of_values + atoi(&value_at_index); // Toggle flag skip_flag = 1; break; case 1: // Add 'even' values together (with multiplier) value_at_index = example_card_num[i]; // 1. Convert each str to int // 2. Multiply by two // 3. Convert back to str in new variable sprintf(sum_to_str, "%d", (atoi(&value_at_index) *2)); // Concatenate each substring to a new string strcat(str_of_evens, sum_to_str); // Toggle flag skip_flag = 0; break; } } // int random_integer = 0; // char random_character = 'M'; char value_at_index_two; for (int i = 0; i < strlen(str_of_evens); i++) { value_at_index_two = str_of_evens[i]; sum_of_values = sum_of_values + atoi(&value_at_index_two); } printf("~~~~~~~~~~~\n"); printf("Sum of Values 01: %d\n", sum_of_values); // Terminate the program return 0; }

然后将其切换为评论并重新编译

改造了
int random_integer = 0;

char random_character = 'M';
  • i还试图稍微更改输入(即
  • char sum_to_str[3];
  • ),以确定是否有一些抛出任意的“ 9”或是否更改了附件的数字。
    	
    您不应在非字符串阵列变量上使用ATOI,因为不能保证将其终止终止,因此ATOI会产生不可预测的结果。
  • 您的问题是由于记忆使用不当而导致的不确定行为引起的:
    非字母化
  • char sum_to_str[3];
→它包含垃圾数据,这会导致

example_card_num[]

行为不可预测

在一个字符上使用
c clang
2个回答
1
投票

strcat()

期望一个无效的字符串,但是您正在传递一个字符

1
投票
中的buffer溢出

atoi()

    atoi()
  1. 太小,无法安全地存储两个数字
    
    我正在附上更正的版本:
    sum_to_str
  2. 
    
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.