简体   繁体   English

使用 Function 将 Char 数组转换为 Int 数组

[英]Converting a Char Array into an Int array using a Function

I have been tasked with converting a char* array into an int array using a function. I'm new to C so I do apologize if this is a simple fix or an easy solution that I have just failed to notice.我的任务是使用 function 将 char* 数组转换为 int 数组。我是 C 的新手,所以如果这是一个简单的修复或我刚刚没有注意到的简单解决方案,我深表歉意。

This is the code I currently have:这是我目前拥有的代码:

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

int convert(char* str[], int length);

int main(void)
{
    int result[50], i, length = 4;
    char *str[] = {"7", "1", "14", "15"};

    result[4] = convert(str, 4);
    for(i = 0; i < length; i++) 
    {     
        printf("%d ", result[i]);
    }
    printf("\n");
    return 0;
}

int convert(char* str[], int length)
{
    int i;
    int arr[50];

    for(i = 0; i > length; i++)
    arr[i] = atoi(str[i]);

    return arr[50];
}

The output is currently this: output 目前是这样的:

832 832 832 832 

Essentially, what the code is attempting to do is convert本质上,代码试图做的是转换

char *str[] = {"7", "1", "14", "15"};

into this (output):进入这个(输出):

7 1 14 15

Any help would be appreciated: :)任何帮助,将不胜感激: :)

Moved the definition of convert() above above main() so the prototype is not required.convert()的定义移到main() ) 之上,因此不需要原型。 As you know the size of the result array it is cleaner to pass it in as an argument, and as @kaylum noted above, the return type of int is clearly incorrect.正如您知道result数组的大小,将它作为参数传递更清晰,并且正如@kaylum 上面指出的那样, int的返回类型显然是不正确的。 The loop is wrong (should be i < length ).循环是错误的(应该是i < length )。 You cannot return a local array arr even if you tried as it will be out of scope when function returns.即使您尝试过,也不能返回本地数组arr ,因为当 function 返回时,它会超出 scope。 return arr[50] refers to an element that is out of bounds. return arr[50]指的是越界的元素。 In main() , the expression result[4] = sets the 4th element and rest of result contains undefined data.main()中,表达式result[4] =设置第 4 个元素,结果的 rest 包含未定义的数据。

#include <stdio.h>
#include <stdlib.h>
#define ARRAY_LEN(A) (sizeof(A) / sizeof(*A))

void convert(int length, char *str[length], int result[length]) {
    for(int i = 0; i < length; i++)
        result[i] = atoi(str[i]);
}

int main(void) {
    char *str[] = {"7", "1", "14", "15"};
    int result[ARRAY_LEN(str)];
    convert(ARRAY_LEN(str), str, result);
    for(int i = 0; i < ARRAY_LEN(result); i++) {
        printf("%d ", result[i]);
    }
    printf("\n");
}

Consider using strtol() instead of atoi() so you can implement error handling ( atoi() returns 0 on error).考虑使用strtol()而不是atoi()以便您可以实现错误处理( atoi()在错误时返回 0)。

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

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