1

The problem here is that whenever I change the contents of studName the contents inside studArr change too.

If the input looks like this (AAA,BBB,CCC) I first store AAA inside studName and then store studName into studArr.

I'm trying to make:

studArr[0][1] = "AAA"

studArr[0][2] = "BBB"

studArr[0][3] = "CCC

but when I use this code all of them equal CCC. Is there a way I can fix this?

for (j = 0; j < NumCourses + 1; j++){
    i = 0;
    k = 0;
    while ((c = fgetc(ifp)) != ')'){
        if (c == ','){
            studName[3] = '\0'; // ends sting with null char
            studArr[j][k+1] = studName;
            k++;
            i = 0;
        }
        else{
            studName[i] = c;
            i++;
        }
    }
    studName[3] = '\0'; // ends sting with null char
    studArr[j][k+1] = studName; // store studName in studArr

}
3
  • Welcome to Stack Overflow! Please take the tour and read How to Ask to learn what we expect from questions here. Commented Aug 19, 2015 at 14:14
  • char* studArr[NumCourses][1024]; char studName[3]; where NumCourses is just a constant Commented Aug 19, 2015 at 14:24
  • 1
    If you store studName[3] = '\0'; than you should declate char studName[4]; In C array index is counted from 0 to N-1, where N is number of elements in the array Commented Aug 19, 2015 at 14:32

3 Answers 3

4

with the assignment:

studArr[j][k+1] = studName;

you store a pointer to char[] studName. You should allocate memory for every instance, like here:

studArr[j][k+1] = strdup(studName);

Note: remember to free allocated memory.

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

Comments

2

studName is a pointer, and each studArr[j][N] is being set to the same pointer. The contents found by the pointer are being updated, but all the duplicate copies of the same pointer will show the last contents only.

You probably need to use strncpy(), or the like. Specific details really depend on the code you have not yet shown, like declarations.

Comments

1

My guess it's because you assign all pointer to point to studName, and it will always contain the last read string.

You need to duplicate the string instead of just assigning the pointer. Either use strdup (which means you have to free the memory later) or make each entry an array and copy into it.

Comments

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.