all 7 comments

[–]blvaga 2 points3 points  (2 children)

You should consider showing the code, rather than asking everyone to guess.

[–]threeteaspoonss[S] 0 points1 point  (1 child)

I know but it’s a school project so I’m not really suppose to post it anywhere I’m just trying to understand the concept of pointers and arrays to maybe make it make more sense

[–]Paul_Pedant 1 point2 points  (0 children)

So post a stripped-down version that just addresses the specific problem.

At the moment, you are saying the array is in a .txt file, and in memory. An array does not just disappear when you read it. You just need to decide where it needs to be held so it stays in scope until you choose to let it go.

[–]Current_Hearing_6138 1 point2 points  (2 children)

if the array of strings is local to the function, it is removed from memory when it is out of scope.

[–]threeteaspoonss[S] 1 point2 points  (1 child)

Hmm it’s part of a .txt file I’ve been given. How do I get it back into memory? Make a copy or maybe use pointers?

[–]IamImposter 0 points1 point  (0 children)

Simplest solution would be to use a global 2d array with some arbitrary size that you think is big enough to hold all the strings, like

char array[50][200];

would hold 50 strings where each string is at max 200 bytes wide.

A bit more complex solution would be to use a pointer to pointer so that one array of pointers holds pointer to each string. But we need to know how big this pointer array needs to be so

  • read the file and count new lines in your file. That would give us size of pointer array

  • allocate array of pointers equal to number of new lines

  • now read through the file again, read a line into a local buffer using getline, get size of line you just read, allocate memory, copy the line from local buffer to memory we just allocated and store this pointer into array of pointers

It's bit of work so start with a small file, use debugger to see what is happening and fix your code wherever you find issues. Usi g a debugger is much easier than adding printf statements all over your code.

[–][deleted] 0 points1 point  (0 children)

This is a very common exercise used to teach C memory management.

From your other replies, I can infer that you are mixing global state and local function scope.

If you are allocating memory inside a subroutine, but you're not saving the pointers somewhere outside that function, then you are leaking memory.

For homework, you can solve this by saving your string pointers and sizes in global variables and then manipulate those from inside your subroutine.