将值放入char 2D数组中

时间:2013-12-29 18:14:52

标签: c arrays

我尝试将两个整数的值放入char数组中。 如果我有:

x = 3;
y = 5;

然后我想要

links[0][0] = "3,5";

我现在有这个代码,但我不知道如何继续。

char** links = (char**) calloc(SRTM_SIZE, sizeof(char*));
if(links)
{
    for(int i = 0; i < SRTM_SIZE; i++)
    {
        links[i] = (char*)calloc(SRTM_SIZE, sizeof(char));
        //memset(links[i], 0, sizeof(*links[i] * SRTM_SIZE));
    }
}

x = strtok(temp, ",");
y = strtok(NULL, ",");

int xx = atoi(x);
int yy = atoi(y);

//Some calculation with x and y and if it's okay, then I need to put value of x and y to array, but I don't know how

printf("%s\n", links[0][0]);

编辑:

我究竟需要的是矩阵(可能是1201x1201)的字符串。进入单元格(不是全部,但可以进入大多数)我需要输入字符串值。该值可以从“0,0”到“1200,1200”。稍后在程序中我需要访问具有字符串值的所有单元格,因为每个值都是相邻单元格之一的位置。

4 个答案:

答案 0 :(得分:1)

links[0][0]是单字节的。您只能存储1个字节,即一个字符。这两个字符将存储在两个不同的内存位置,例如link[0][0]link[0][1]。然后,您还需要\0字符才能使用%s进行打印 声明

printf("%s\n", links[0][0]);  

错误%s用于字符串,但links[0][0]char 你可以这样做

sprintf(links[0], "%d,%d", xx,yy);
printf("%s\n", links[0]);   

更改后测试代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SRTM_SIZE 5

int main(void){
    char** links = (char**) calloc(SRTM_SIZE, sizeof(char*));
    if(links)
    {
        for(int i = 0; i < SRTM_SIZE; i++)
        {
            links[i] = (char*)calloc(SRTM_SIZE, sizeof(char));
            //memset(links[i], 0, sizeof(*links[i] * SRTM_SIZE));
        }
    }

    char temp[5]="2,3";
    char *x = strtok(temp, ","); //strtok() returns pointer to char.
    char *y = strtok(NULL, ",");

    int xx = atoi(x);
    int yy = atoi(y);
    sprintf(links[0], "%d,%d", xx,yy);
    //Some calculation with x and y and if it's okay, then I need to put value of x and y to array, but I don't know how

    printf("%s\n", links[0]);

}

答案 1 :(得分:1)

使用sprintf

sprintf(links[0][0],"%d,%d",x,y);

但在更改链接[0] [0]到字符串(字符*)

之前

"3,5" is string not a character.

更多信息http://www.cplusplus.com/reference/cstdio/sprintf/

答案 2 :(得分:0)

您无法按照自己的方式为2D数组赋值。这是它的工作原理:

arr[0][0]= x;

arr[0][0]指的是单个位置,即第0行和第0列。

如果您有arr[2][2],则必须指定将值放在2D数组中的位置。如果你想要它在第一行,在最后一列:

arr[0][2]= x;

您可以按如下方式显示2D数组:

int  arr[3][2]:

             column 0     column 1

row 0       |arr[0][0]| |arr[0][1]|
row 1       |arr[1][0]| |arr[0][1]|
row 2       |arr[2][0]| |arr[0][1]| 

答案 3 :(得分:0)

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

int main(void){
    int len;
    int x = 3, y = 5;
    len = snprintf(NULL, 0, "%d,%d", x, y);
    char *link = malloc(len + 1);
    sprintf(link, "%d,%d", x, y);
    printf("%s\n", link);
    free(link);
    return 0;
}
相关问题