'How to take the first letter of a string pointer?

First of all, I know it is such a common topic that I can find millions of example. Yet, I still did not understand the idea. So please forgive me about asking this for a million time.

char *char_name = strtok(NULL,","); // Which gives me a part of the string such as "Albert"
char** map; // Which is actually a board game representation.

So let me explain what I try to understand. Column and row integers are given, let us say. Then I need to change that position's character to the first character of the char *char_name, which is 'A' in the 'Albert' example.

map[row][column] = char_name[0]; // Does not work since char_name is a pointer.

Believe me, I tried almost everything I saw in internet.Thus, I do not want to bore you with my random attempts. Yet, still does not work. What should I do?



Solution 1:[1]

Let me see how good my crystal ball is today. (I felt like it.)

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

#define GRIDSIZE 10

int main( int argc, char * argv[] )
{
    char * input;
    char * char_name;

    size_t row;
    size_t col;

    char ** map;

    if ( argc != 2 )
    {
        puts( "Please give one string of comma-separated names as parameter." );
        return 0;
    }

    // Allocate memory
    input = malloc( strlen( argv[1] ) + 1 );
    strcpy( input, argv[1] );

    map = malloc( sizeof( char * ) * GRIDSIZE ); // memory for GRIDSIZE rows

    for ( row = 0; row < GRIDSIZE; ++row )
    {
        map[row] = malloc( GRIDSIZE ); // memory for GRIDSIZE columns
        memset( map[row], ' ', GRIDSIZE );
    }

    // Place characters
    char_name = strtok( input, "," );
    row = 0;
    col = 0;

    while ( ( char_name != NULL ) && ( row < GRIDSIZE ) )
    {
        map[row][col] = char_name[0];
        ++row;
        char_name = strtok( NULL, "," );
    }

    // Print grid
    for ( row = 0; row < GRIDSIZE; ++row )
    {
        for ( col = 0; col < GRIDSIZE; ++col )
        {
            printf( "%c.", map[row][col] );
        }
        printf( "\n" );
    }

    // Free memory
    for ( row = 0; row < GRIDSIZE; ++row )
    {
        free( map[row] );
    }

    free( map );
    free( input );
}

(Version 2, taking input from command line.)

I omitted all the checks if malloc() returned non-NULL, which should be in there if you are writing something non-trivial.

Input:

myprog "Albert,Berta"

Output:

A. . . . . . . . . .
B. . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .
 . . . . . . . . . .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1