简体   繁体   中英

adding an int to a Multi-dimensional char Array

I am trying to add an int to a Multi-dimensional char Array. After reading the link below I would think I can use sprintf. If I can't use sprintf what is another way I can do this?

http://www.cplusplus.com/reference/cstdio/sprintf/

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


int main(int argc, char *argv[])
{
    //{"TYPE", "ID", "SCOPE", "VALUE"}
    char *symbol_table_variables[503][4];
    int scope = 0;
    int lower_bound_of_big_boy_counter = 0;
    sprintf (symbol_table_variables[lower_bound_of_big_boy_counter][2], "%d", scope);
    printf("symbol_table_variables[lower_bound_of_big_boy_counter][2] %s \n", 
    symbol_table_variables[lower_bound_of_big_boy_counter][2]);
    return 0;
}

An update.

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


int main(int argc, char *argv[])
{
    //{"TYPE", "ID", "SCOPE", "VALUE"}
    char *symbol_table_variables[503][4] = {0};
    int scope = 5;
    int lower_bound_of_big_boy_counter = 0;
    char scope_char[80] = {0};

    sprintf (scope_char, "%d", scope);
    printf("scope_char %s \n", scope_char);

    symbol_table_variables[lower_bound_of_big_boy_counter][2] = 
    malloc(strlen(scope_char)+1);

    strcpy(symbol_table_variables[lower_bound_of_big_boy_counter][2], 
    scope_char);
    memset(scope_char, 0, 80);

    //sprintf (symbol_table_variables[lower_bound_of_big_boy_counter][2], "%d", scope);
    printf("symbol_table_variables[lower_bound_of_big_boy_counter][2] is %s \n", 
    symbol_table_variables[lower_bound_of_big_boy_counter][2]);
    return 0;
}

symbol_table_variables[lower_bound_of_big_boy_counter][2] has no memory allocated to it you you are invoking undefined behavior.

One solution would be to allocate some memory

symbol_table_variables[lower_bound_of_big_boy_counter][2] = malloc(32);
printf (symbol_table_variables[lower_bound_of_big_boy_counter][2], "%d", scope);

That isn't great because you don't really know how much memory you need.

I'd be questioning the need for a 2D array of strings...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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