简体   繁体   English

如何在 c 编程中处理一维数组的索引?

[英]How can I approach index of one dimensional array in c programming?

input
1 2
2 3
1 5
5 2
5 6
4 7

If i receive 6 strings including blank, I want to change them to integers such as如果我收到包括空白在内的 6 个字符串,我想将它们更改为整数,例如

output
12
23
15
52
56
47

how can i make this program in c??我怎样才能在 c 中制作这个程序?

int input_strings(int arraySize){
scanf("%d",&arraySize); 
char * names[arraySize];
char buffer[30]; 
int n = 0;
int l = 0;

while ( n < arraySize ) {
    scanf("%s", buffer);
   
    
    l = strlen(buffer);
    if (l > 0){
        char* newstrptr = (char*)malloc(sizeof(char) * (l + 1));
        strcpy(newstrptr, buffer);
        names[n] =  newstrptr;
        n++;
    } else {
        break;
    }
}



for(n=0;n<arraySize;n++){
    printf("%02d: %s\n", n, names[n]);
    free(names[n]);
}
return 0;
}

after this code, there will be names[0] ~ names[5]在这段代码之后,会有names[0] ~ names[5]
First question, I want to delete blank that is 2nd index of names[0].第一个问题,我想删除名称 [0] 的第二个索引的空白。 For example, names[0] = "1 2", and I want to delete and make "12".例如,names[0] = "1 2",我想删除并制作“12”。

Second, How can i approach 2nd index of array?其次,我怎样才能接近数组的第二个索引? If new_names[0] = "12", then How can I approach 2nd index of new_names[0]?如果 new_names[0] = "12",那么我怎样才能接近 new_names[0] 的第二个索引? should I use two dimensional array?我应该使用二维数组吗?

Does it answer your question?它回答了你的问题吗? (I assume that your individual numbers cannot have more than 1 digit) (我假设您的个人号码不能超过 1 位)

Question 1问题 1

#include <stdio.h>
int main() {
    char * str = malloc(4);
    strcpy(str, "1 2");
    str[1] = str[2];
    str[2] = 0;
    printf("%s\n", str); //==> "12"
    free(str);
    return 0;
}

Question 2问题2

#include <stdio.h>
int main() {
    char * str = "12";
    int n = str[1] - '0';
    printf("%d\n", n); //==> 2
    return 0;
}

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

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