0

I'm trying to store characters read from a file into an array of characters, but it ends up storing every succeeding character as well. For this code, I created a structure and a function to initialize the array.

From "Structures.h"

typedef struct (
    int size;
    char *elem;
    } cvector;

From "Utilities.c"

cvector make_cvector (int size)
    {   cvector temp;
        temp.size = size;
        temp.elem = calloc(size, sizeof(char));
        return temp;
    }

Then I'm trying to read a text file that says: "a b c"

In the body, I stated: (where nPtr is the pointer for opening the file)

cvector NodeID;
NodeID = make_cvector(3);
for(i=0;i<3;i++){
        fscanf(nPtr,"%s", &NodeID.elem[i]);
        printf("%s ",&NodeID.elem[i]);
}

This results in " a b c " But right after this loop, I typed another loop:

for(i=0;i<3;i++)
        printf("%s ", &NodeID.elem[i]);

Resulting to "abc bc c" When in fact I want "a" "b" and "c" stored separately. There's probably something wrong with my initialization or pointers, but I've been trying to read up online to no avail. Where could the error be? Thank you!

1 Answer 1

2

You are printing a string when what you really want to do is printing a single character. Replace

printf("%s ",&NodeID.elem[i]);

by

printf("%c ",NodeID.elem[i]);

and it should work.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for that and I understand the error. However, the printing was just a means to demonstrate my problem. The real problem I encountered was in a latter part where I put: if(strcmp(LoadLoc, &NodeID.elem[j])==0) which basically never happened. I suppose the error then isn't with initialization, but with the use of "strcmp" what would be a suitable alternative? :D I'll try to search online as well. Thank you very much sir!
LoadLoc is a string containing a single character, right? If so then store LoadLoc in a char instead and do if (LoadLoc == NodeID.elem[j])
Thanks! This worked, but I wanted to maintain a certain level of universality as some parts of the program might shift to comparing strings and not just characters. Anyway, I solved the problem by initializing them as "cmatrix" instead of "cvector" where the 1st dimension is an array of strings, and the second dimension an array of characters per string. Thanks for all the help! :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.