How to convert char pointer into char in C Open VMS

28.6k views Asked by At

This is to convert from char pointer into char.

I followed the codes from another topic but it seems like it's not working to me. I am using Open VMS Ansi C compiler for this. I don't know what's the difference with another Platform.

main(){

char * field = "value1";
char c[100] = (char )field;

printf("c value is %s",&c);

}

the output of this is

c value is

which is unexpected for me I am expecting

c value is value1

hope you can help me.

3

There are 3 answers

0
Matthew Flaschen On
strcpy(c, field);

You must be sure c has room for all the characters in field, including the NUL-terminator. It does in this case, but in general, you will need an if check.

EDIT: In C, you can not return an array from a function. If you need to allocate storage, but don't know the length, use malloc. E.g.:

size_t size = strlen(field) + 1; //  If you don't know the source size.
char *c = malloc(size);

Then, use the same strcpy call as before.

2
Dmitri On

In C, the char type holds a single character, not a string. char c[100]; doesn't allocate a char of length 100, it allocates an array of 100 consecutive chars, each one byte long, and that array can hold a string.

So what you seem to want to do is to fill an array of chars with the same char values that are at the location pointed at by a char *. To do that, you can use strncpy() or any of several other functions:

strncpy(c,field,100); /* copy up to 100 chars from field to c */
c[99] = '\0';         /* ..and make sure the last char in c is '\0' */

..or use strcpy() since you know the string will fit in c (better in this case):

strcpy(c,field);

..or:

snprintf(c,100,"%s",field);
1
Cindy Adriana Bohrquez Santana On
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){

    char * field = "value";

    char c[100]="";
    strncpy(c,field,100);

    printf("c value is %s",c);
    return 0;
}